自动装箱与拆箱

自动装箱与拆箱

代码如下:

package ClassDemo; public class AutoLoadingDemo { public static void main(String[] args) {
//装箱?,相当于编译器自动作以下的语法编译:Integer testVar1 = Integer.valueOf(100);
Integer testVar1 = 100;
//拆箱,实际上执行了 int t = i.intValue();
int testVar2 = testVar1;
System.out.println(testVar1);
System.out.println(testVar2);

//方法调用时
System.out.println("testVar1 is Integer?" + (testVar1 instanceof Integer));
autoLoadingMethodDemo(testVar1);
autoLoadingMethodDemo(testVar2);


/**
* 自动装箱容易混乱的对象和原始数据值
* 一个具体的例子就是当我们在一个原始数据值与一个对象进行比较时,
* 如果这个对象没有进行初始化或者为Null,在自动拆箱过程中obj.xxxValue,
* 会抛出NullPointerException,如下面的代码:
*/
// Integer count;//Integer count = null;
// if( count <= 0) {//count.intValue();
//
// }
} private static void autoLoadingMethodDemo(int testVar) {
// 测试方法的自动装箱
System.out.println("testVar in the method (int):" + testVar);
}

private static void autoLoadingMethodDemo(Integer testVar) {
// 测试方法的自动装箱的重载
System.out.println("testVar in the method (Integer):" + testVar);
}
}

希望有所帮助

posted @ 2017-06-20 18:38  辰峰  阅读(97)  评论(0编辑  收藏  举报