Java基础知识强化66:基本类型包装类之JDK5新特性自动装箱和拆箱

1. JDK1.5以后,简化了定义方式。

(1)Integer  x = new  Integer(4);可以直接写成如下:

        Integer  x = 4 ;//自动装箱,通过valueOf方法。

备注:valueOf方法 (int --->  Integer)

1 static Integer valueOf(int i) 
2                                 Returns a Integer instance for the specified integer value. 
3 static Integer valueOf(String string) 
4                                 Parses the specified string as a signed decimal integer value. 

(2)x = x+5;//自动拆箱。通过intValue方法。

备注:intValue方法(Integer--->int)

 int    intValue() 
                   Gets the primitive value of this int.

2. 需要注意:

(1)在使用时候,Integer  x = null ;上面的代码就会出现NullPointerException。

3. 案例演示:

 1 package cn.itcast_05;
 2 
 3 /*
 4  * JDK5的新特性
 5  * 自动装箱:把基本类型转换为包装类类型
 6  * 自动拆箱:把包装类类型转换为基本类型
 7  * 
 8  * 注意一个小问题:
 9  *         在使用时,Integer  x = null;代码就会出现NullPointerException。
10  *         建议先判断是否为null,然后再使用。
11  */
12 public class IntegerDemo {
13     public static void main(String[] args) {
14         // 定义了一个int类型的包装类类型变量i
15         // Integer i = new Integer(100);
16         Integer ii = 100;
17         ii += 200;
18         System.out.println("ii:" + ii);
19 
20         // 通过反编译后的代码
21         // Integer ii = Integer.valueOf(100); //自动装箱
22         // ii = Integer.valueOf(ii.intValue() + 200); //自动拆箱,再自动装箱
23         // System.out.println((new StringBuilder("ii:")).append(ii).toString());
24 
25         //Integer iii = null;
26         // NullPointerException
27         if (iii != null) {
28             iii += 1000;
29             System.out.println(iii);
30         }
31     }
32 }

注意:

(1)Integer  ii = 100;                    等价于:

        Integer ii = Integer.valueOf(100);

通过反编译.class文件知道,这里自动jvm执行这个代码(jvm执行.class文件)时候,实现了自动装箱。

(2) ii += 200;                               等价于:

         ii = Integer.valueOf(ii.intValue() + 200);  //自动拆箱,再自动装箱

(3)System.out.println("ii:" + ii);     等价于:

System.out.println((new StringBuilder("ii:")).append(ii).toString());

内部使用StringBuilder进行字符串拼接。

原文地址:https://www.cnblogs.com/hebao0514/p/4836348.html