关于boxing和unboxing的Java面试题

来源:互联网 发布:app吓人软件 编辑:程序博客网 时间:2024/04/29 20:07

先看代码:

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); // trueInteger 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); // falseInteger a1 = 127;Integer b1 = 127;System.out.println(a1==b1); // trueInteger a2 = 128;Integer b2 = 128;System.out.println(a2==b2); // falseShort s = new Short((short) 100);Short t = new Short((short) 100);System.out.println(s==t); // falseShort s1 = 127;Short t1 = 127;System.out.println(s1==t1); // trueShort s2 = 128;Short t2 = 128;System.out.println(s2==t2); // falseCharacter c = new Character('a');Character d = new Character('a');System.out.println(c==d); // falseCharacter c1 = 'a';Character d1 = 'a';System.out.println(c1==d1); // trueCharacter c2 = '※';Character d2 = '※';System.out.println(c2==d2); // false}}