关于boxing和unboxing的Java面试题

本文深入探讨了Java中Integer的装箱与拆箱过程,包括其对象创建机制及不同数据范围内的行为特性。通过具体代码实例,详细解释了Integer对象的比较逻辑,以及基础数据类型超出默认取值范围时如何自动转化为对象。

先看代码:

public class Testboxing {

	public static void main(String[] args) {
		Integer a = new Integer(40);
		Integer b = new Integer(40);
		System.out.println(a==b);

		Integer a1 = 127;
		Integer b1 = 127;
		System.out.println(a1==b1); // true

		Integer a2 = 128;
		Integer b2 = 128;
		System.out.println(a2==b2); // false
	}

}

结果:

1. false

2. true

3. false
原因分析

1. 只要是new Integer,不管数据是多少总是建立新的对象,a==b总是false

2. 如果不是new Integer,且取值范围在-128~127之间时,JVM不建立对象,a==b是true

3. 如果不是new Integer,且取值范围超出-128~127时,JVM建立对象,a==b是false

装箱boxing就是把基础数据类型包装成对象。如:

Integer a = new Integer() ;
a = 100 ;

拆箱unboxing就是把对象转换成基础数据类型。如:

int b = new Integer(100) ;

Java默认的基础类型取值范围是:

boolean:true 和 false 
全部的byte 值 
short: -128 和 127 之间
int:  -128 和 127之间 
char: 从  \u0000 到 \u007F(0-127基本ASCII的范围)

如果超出上述范围,JVM自动建立对象,而不是基础类型。

完整的测试代码:

public class TestBoxing {

	public static void main(String[] args) {
		Integer a = new Integer(40);
		Integer b = new Integer(40);
		System.out.println(a==b); // false

		Integer a1 = 127;
		Integer b1 = 127;
		System.out.println(a1==b1); // true

		Integer a2 = 128;
		Integer b2 = 128;
		System.out.println(a2==b2); // false
		
		Short s = new Short((short) 100);
		Short t = new Short((short) 100);
		System.out.println(s==t); // false
		
		Short s1 = 127;
		Short t1 = 127;
		System.out.println(s1==t1); // true
		
		Short s2 = 128;
		Short t2 = 128;
		System.out.println(s2==t2); // false
		
		Character c = new Character('a');
		Character d = new Character('a');
		System.out.println(c==d); // false
		
		Character c1 = 'a';
		Character d1 = 'a';
		System.out.println(c1==d1); // true
		
		Character c2 = '※';
		Character d2 = '※';
		System.out.println(c2==d2); // false
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值