Java包装类Wrapper

包装类

针对8种基本数据类型相应的引用类型。——包装类。

Boolean、Character、Byte、Short、Integer、Long、Float、Double。

具有类的特点,可以调用类中的方法。他们都是Number的子类。

包装类和基本数据类型的转换。

装箱:基本类型——>包装类型。反过来为拆箱。

jdk5之后,就可以实现自动装箱和拆箱了。自动装箱底层调用的是valueOf()方法。

public class Wrapper01 {
    public static void main(String[] args) {
       int n1 = 100;
       Integer integer = n1;//自动装箱,底层使用的仍然是Integer.valueOf()方法
       int n3 = integer;//自动拆箱
        
        //手动装箱 两种写法
        int n2 = 200;
        Integer integer1 = new Integer(n2);
        Integer integer2 = Integer.valueOf(n2);
        //手动拆箱
        int i = integer1.intValue();
    }
}
public class Wrapper02 {
    public static void main(String[] args) {
        Object obj = true?new Integer(1):new Double(2.0);
        System.out.println(obj);
        //上面是一个三元运算符,如果第一个为真,则返回第二个值,反之,返回第三个值。
        //但注意不是1,而是1.0.因为含有有double,会自动类型转换。三元运算符是一个整体
    }
}
1.0

Process finished with exit code 0

包装类与String类的相互转换

public class Wrapper03 {
    public static void main(String[] args) {
        //包装类——>String类
        Integer i = 100;//自动装箱
        String str = i + "";//方式1
        String str2 = i.toString();//方式2
        String str3 = String.valueOf(i);//方式3

        //String类——>包装类
        String str4 = "123";
        Integer i1 = Integer.parseInt(str4);//方式1
        Integer integer = new Integer(str4);//方式2
    }
}
public class Wrapper04 {
    public static void main(String[] args) {
        Integer integer = new Integer(1);
        Integer integer2 = new Integer(1);
        System.out.println(integer == integer2);//是两个新的对象
        //查看底层valueOf的源码,如果在-128~127,直接从数组中取,不会new一个Integer。
        Integer m = 1;
        Integer n = 1;
        System.out.println(m == n);

        Integer x = 128;
        Integer y = 128;
        System.out.println(x == y);

    }
}
false
true
false

Process finished with exit code 0

只要有基本数据类型,==判断的就是值是否相等

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值