Java Wrapper包装类 类型转换 详解!!!

Wrapper包装类

什么是包装类?

基本数据类型包装类
byteByte
intInteger
longLong
shortShort
doubleDouble
floatFloat
booleanBoolean
charCharacter

为什么需要有包装类?

包装类让java中的基本数据类型拥有像类一样的属性,可以使用方法,完善Java面向对象的概念

基本数据类型 包装类 String类型 三者的相互转化

基本数据类型→包装类

1.使用包装类的构造器

//构造器中填入基本数据类型   
int i = 1;
Integer in1 = new Integer(i);
//构造器中填入对应的字符串
Integer in2 = new Integer("1");

2.自动装箱 (主要使用)

Integer in3 = i;

包装类→基本数据类型

1.使用包装类的方法xxxValue()

int i1 = 1;
Integer in1 = 5;
i1 = in1.intValue();

2.自动拆箱(主要使用)

int i1 = 1;
Integer in1 = new Integer("3");
i1 = in1;
System.out.println(in1);
tips:因为有自动拆箱和自动装箱,包装类和基本数据类型的界限就大大缩小

基本数据类型,包装类→String类型

通过String的valueOf()方法(主要使用)

int i1 = 1;
Integer in1 = new Integer("3");

String str1 = new String();
str1 = String.valueOf(i1);
str1 = String.valueOf(in1);

String类型→基本数据类型,包装类

通过Xxx.parseXxx()方法(主要使用)

String str1 = new String();
str1 = "123";
Integer in2 = Integer.parseInt(str1);
int i2 = Integer.parseInt(str1);

测试:

test1

private static void test1() {
   Object o1 = true ? new Integer(1) : new Double(2.0);
   System.out.println(o1); // 1.0
}
为什么返回1.0呢 ? 因为使用三元运算符,需要保证三元运算符两边的数字类型相同,又因为自动类型提升,使得Integer的类型自动提升为Double 导致1→1.0

test2

private static void test2() {
        Integer in1 = new Integer(1);
        Integer in2 = new Integer(1);
        System.out.println(in1 == in2);//false

        Integer in3 = 1;
        Integer in4 = 1;
        System.out.println(in3 == in4);//true

        Integer in5 = 128;
        Integer in6 = 128;
        System.out.println(in5 == in6);//false
    }
第一个System.out.println返回的值是false这是因为,Integer类是一个引用类型,== 所比较的就是地址值,new了两个对象他们的地址值自然是不同的。
第二个System.out.println返回的值是true以及第三个System.out.println返回的值为false的原因是,第二个和第三个使用的都是自动装箱,在Integer这个类内部生成时已经产生了一个-128到127的数组,使用时只是在这个数组中获取(提高使用效率,因为-128到127的值使用的较为频繁)因为内存中已经存储好了这个数组空间,使用时直接获取(in3和in4都是直接从数组里获取的)所以在这个范围内的相同值地址也是一样的,通过==进行判断时,这两个值是相同的。
而第三个System.out.println不同是因为128超过了提前定义好的数组范围,所以这个128不能直接从数组里获取,只能通过new的方式产生。而new出来的两个对象的地址值一定是不同的,这就导致==判断为false
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值