JDK5.0新特性系列---1.自动装箱和拆箱

/**

 * 基本类型的数据值可以直接赋给基本数据对象,基本数据的对象也可以直接赋给基本数据变量

 * 在表达式中,基本类型的数据值可以和基本数据对象进行运算

 * 基本数据类型的数组不能实现自动装箱和拆箱,int[]不能当成Integer[]使用

 */

/**

 * 演示基本数据类型的自动拆箱和装箱

 */

public class AutoBox {

       /**整数类型的自动拆箱和装箱*/

       public static void intAutoBox(){

              //可以装基本数字类型赋给数字对象

              //J2SE之前,必须用iObj = new Integer(200);

              int i = 100;

              Integer iObj = 200; //200装箱

              System.out.println("开始时: i = " + i + "; iObj = " + iObj);

             

              //将数字对象赋给基本数字类型

              //J2SE5.0之前,必须使用i = tempObj.intValue();

              Integer tempObj = iObj;

              iObj = i;

              i = tempObj;  //将对象拆封

              System.out.println("iiObj的值互换后: " + "i = " + i + "; iObj = " + iObj);

             

              //在表达式内可以自动拆箱和装箱

              iObj += i + tempObj;

              i *= iObj + tempObj;

              System.out.println("i = " + i +"; iObj = " + iObj);

       }

      

       /**boolean类型的自动拆箱与装箱*/

       public static void booleanAutoBox(){

              boolean b = false;

              Boolean bObj = true//装箱

              if(bObj){//拆箱

                     System.out.println("bObj = " + true);

              }

              if(b || bObj){

                     b = bObj; //拆箱

                     System.out.println("bObj = " + bObj +"; b = " + b);

              }

       }

      

       /**字符类型的自动拆箱与装箱*/

       public static void charAutoBox(){

              char ch = 'A';

              Character chObj = 'B';

              System.out.println("ch = " + ch + "; chObj = " + chObj);

              if(ch != chObj){ //拆箱

                     ch = chObj; //拆箱

                     System.out.println("ch = " + ch + "; chObj = " + chObj);

              }

       }

      

       public static void main(String[] args){

              intAutoBox();

              booleanAutoBox();

              charAutoBox();

              //注意,支持基本数据类型的自动拆箱和装箱,但是不支持基本类型数组的自动拆箱和装箱

              int[] is = {12,34,56};

              //Integer[] iObj = is; //error!!!

             

       }

}

 

 

 

 

posted @ 2011-12-17 23:20  远哥  阅读(919)  评论(0编辑  收藏  举报