1.

Q. How does autoboxing handle the following code fragment? (自动装箱怎样处理下面的代码片段 ? )

Integer a = null;
int b = a;

A. It results in a run-time error. Primitive type can store every value of their corresponding wrapper type except null. (会导致一个运行时异常。原始数据类型可以存储其相应包装类型的每个值,null 除外)

2.

Q. Why does the first group of statements print true, but the second false?
译: 为什么第一组语句打印为 true, 第二组打印为 false ?

Integer a1 = 100;
Integer a2 = 100;
System.out.println(a1 == a2);   // true

Integer b1 = new Integer(100);
Integer b2 = new Integer(100);
System.out.println(b1 == b2);   // false

Integer c1 = 150;
Integer c2 = 150;
System.out.println(c1 == c2);   // false

A. The second prints false because b1 and b2 are references to different Integer objects. The first and third code fragments rely on autoboxing. Surprisingly the first prints true because values between -128 and 127 appear to refer to the same immutable Integer objects (Java’s implementation of valueOf() retrieves a cached values if the integer is between -128 and 127), while Java constructs new objects for each integer outside this range.

译: 第二个打印 false 是因为 b1 和 b2 是两个不同 Integer 对象的引用。第一个和第三个代码片段依赖于自动装箱。令人惊讶的是第一个打印为 true,因为介于 -128 和 127 之间的值似乎引用了相同的不可变整数对象 ( 如果该整数介于 -128 和 127 之间,valueOf() 的实现将检索缓存的值 ) 而 Java 会构造新对象用于此范围之外的每个整数。