【Java基础】--05.java 常用类(1)

Java 中包装类

相信各位小伙伴们对基本数据类型都非常熟悉,例如 int、float、double、boolean、char 等。基本数据类型是不具备对象的特性的,比如基本类型不能调用方法、功能简单。。。,为了让基本数据类型也具备对象的特性, Java 为每个基本数据类型都提供了一个包装类,这样我们就可以像操作对象那样来操作基本数据类型。

基本类型和包装类之间的对应关系:

这里写图片描述

包装类主要提供了两大类方法:

  1. 将本类型和其他基本类型进行转换的方法
  2. 将字符串和本类型及包装类互相转换的方法

任务
我们以 Integer 包装类为例,来看下包装类的特性。
Integer 包装类的构造方法:
这里写图片描述
如下代码所示:
这里写图片描述
Integer包装类的常用方法:
这里写图片描述

Demo

public class HelloWorld {
    public static void main(String[] args) {

        // 定义int类型变量,值为86
        int score1 = 86; 

        // 创建Integer包装类对象,表示变量score1的值
        Integer score2=new Integer(score1);

        // 将Integer包装类转换为double类型
        double score3=score2.doubleValue();

        // 将Integer包装类转换为float类型
        float score4=score2.floatValue();

        // 将Integer包装类转换为int类型
        int score5 =score2.intValue();

        System.out.println("Integer包装类:" + score2);
        System.out.println("double类型:" + score3);
        System.out.println("float类型:" + score4);
        System.out.println("int类型:" + score5);
    }
}

这里写图片描述

Java 中基本类型和包装类之间的转换

基本类型和包装类之间经常需要互相转换,以 Integer 为例(其他几个包装类的操作雷同哦):
这里写图片描述
在 JDK1.5 引入自动装箱和拆箱的机制后,包装类和基本类型之间的转换就更加轻松便利了。
那什么是装箱和拆箱呢?我们分别来看下
装箱:把基本类型转换成包装类,使其具有对象的性质,又可分为手动装箱和自动装箱

这里写图片描述

拆箱:和装箱相反,把包装类对象转换成基本类型的值,又可分为手动拆箱和自动拆箱
这里写图片描述

Demo

完成了基本类型和包装类之间的转换,即装箱和拆箱的操作。

public class HelloWorld {
    public static void main(String[] args) {

        // 定义double类型变量
        double a = 91.5;

        // 手动装箱
        Double b =  new Double(a);      

        // 自动装箱
        Double c =  a;     

        System.out.println("装箱后的结果为:" + b + "和" + c);

        // 定义一个Double包装类对象,值为8
        Double d = new Double(87.0);

        // 手动拆箱
        double e =  d.doubleValue();

        // 自动拆箱
        double f =  d;

         System.out.println("拆箱后的结果为:" + e + "和" + f);

这里写图片描述

猜你喜欢

转载自blog.csdn.net/YYZZHC999/article/details/81160206
今日推荐