Java的包装类(Wrapper)

一、八大数据类型所对应的包装类 

二、手动装箱与手动拆箱

在JDK1.5之前,只有手动装箱和手动拆箱

1.手动装箱

有两种方式

public class Wrapper {
    public static void main(String[] args) {
        int n1=100;
        //方式1
        Integer i = new Integer(n1);
        //方式2
        Integer i1 = Integer.valueOf(n1);
    }
}

 2.手动拆箱
public class Wrapper {
    public static void main(String[] args) {
        int n1 = 100;
        //方式1
        Integer i = new Integer(n1);
        //方式2
        Integer i1 = Integer.valueOf(n1);
        //手动拆箱
        int i2 = i1.intValue();
    }
}

三、自动装箱与自动拆箱

在JDK1.5及1.5以后,就有自动装箱和自动拆箱

由于几个包装类方法都基本一样,所以本文选用int的包装类Integer作为展示:

1.自动装箱:将int转为Integer
    public static void main(String[] args) {
//        自动装箱
        Integer a = 45;
    }

底层还是调用了 Integer.valueOf( )方法

 2.自动拆箱:将Integer转为int
    public static void main(String[] args) {
//        自动装箱
        Integer a = 45;
//        自动拆箱
        int b = a;
    }

底层还是调用***.intValue( )方法 

四、将包装类转为基本数据类型(手动拆箱)

***Value()方法

    public static void main(String[] args) {
        Integer a = 45;
        int a1 = a.intValue();

        Boolean b=true;
        boolean b1 = b.booleanValue();
        
        System.out.println(a1);
        System.out.println(b1);
    }

五、将基本数据类型转为字符串

//将包装类转换为String类型
public class Wrapper {
    public static void main(String[] args) {
        Integer n1 = 100;
        //方式一
        String string1 = n1 + "";
        //方式二
        String string2 = n1.toString();
        //方法三
        String string3 = String.valueOf(n1);
    }
}

六、将字符串类型转为基本数据类型

包装类.parse***()方法

方式一:

    public static void main(String[] args) {
        int i = Integer.parseInt("45454");
        System.out.println(i);
    }

方式二:

public class Wrapper {
    public static void main(String[] args) {
        String str = "123456";
        int i = new Integer(str);
    }
}

七、Interger和Character类的常用方法

 

*附加知识

很有意思的是,今天学到个新知识,要把三元运算符看作一个整体;

例如:

public class Wrapper {
    public static void main(String[] args) {
       Object obj=true?new Integer(1):new Double(2.0);
        System.out.println(obj);
    }
}

它的输出结果是1.0,而不是1;因为要看成整体,后面是2.0,Double类型,精度需要提升;

对于像这样的问题:

到底输出true还是false呢?

我们可以看见,如果是在-128~127之间,是从数组直接返回,不创建新的对象,这个数组是在类加载时候就自动创建好的。

所以,上面的题目,答案是true 

  • 14
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐晓率

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值