java13-5 JDK1.5以后的一个新特性和Integer的面试题

1、JDK5的新特性

    自动装箱:把基本类型转换为包装类类型

    自动拆箱:把包装类类型转换为基本类型

  注意一个小问题:

    在使用时,Integer x = null;代码就会出现NullPointerException。

  标准化:建议先判断是否为null,然后再使用。

 1 public class IntegerDemo {
 2 public static void main(String[] args) {
 3 // 定义了一个int类型的包装类类型变量i
 4 // Integer i = new Integer(100);
 5 Integer ii = 100;
 6 ii += 200;
 7 System.out.println("ii:" + ii);
 8 
 9 // 通过反编译后的代码
10 // Integer ii = Integer.valueOf(100); //自动装箱
11 // ii = Integer.valueOf(ii.intValue() + 200); //自动拆箱,再自动装箱
12 // System.out.println((new StringBuilder("ii:")).append(ii).toString());
13 
14 Integer iii = null;
15 // NullPointerException
16 if (iii != null) {
17 iii += 1000;
18 System.out.println(iii);
19 } //这一段是死代码,永远进不来
20 }
21 }

2、面试题:

   第一题:

    Integer i = 1;

    i += 1;

  这一段代码做了哪些事情?

  答: Integer i = 1;自动装箱

     i += 1; 自动拆箱,再自动装箱

  第二题:

    看程序写结果

 

 1 public class IntegerDemo {
 2 public static void main(String[] args) {
 3 Integer i1 = new Integer(127);
 4 Integer i2 = new Integer(127);
 5 System.out.println(i1 == i2);
 6 System.out.println(i1.equals(i2));
 7 System.out.println("-----------");
 8 
 9 Integer i3 = new Integer(128);
10 Integer i4 = new Integer(128);
11 System.out.println(i3 == i4);
12 System.out.println(i3.equals(i4));
13 System.out.println("-----------");
14 
15 Integer i5 = 128;
16 Integer i6 = 128;
17 System.out.println(i5 == i6);
18 System.out.println(i5.equals(i6));
19 System.out.println("-----------");
20 
21 Integer i7 = 127;
22 Integer i8 = 127;
23 System.out.println(i7 == i8);
24 System.out.println(i7.equals(i8));

//上面的答案:equals方法的都是true,而 == 的答案依次是:flase,flase,flase,true

// 通过查看源码,我们就知道了,针对-128到127之间的数据,做了一个数据缓冲池,

// 如果数据是该范围内的,就直接从缓冲池里面提取数据,不用创建新的空间

// 如果数据不是这个范围的,则需要重新创建新的空间

// 所以System.out.println(i5 == i6);这里是flase

// Integer ii = Integer.valueOf(127);

}

}

注意:Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据