Java_装箱拆箱

将基本数据类型变为包装类:装箱操作

将包装类基本数据类型取出:拆箱操作

JDK1.5以后可以实现自动装箱拆箱

范例:以Integer为例:

public class TestDemo{

  public static void main(String args[]){

    Integer x = 100; //自动装箱

    int y = x; //自动拆箱

    System.out.println( ++ x * y);  //直接自动拆箱进行计算,结果10100

  }

}

范例:以Double为例:

public class TestDemo{

  public static void main(String args[]){

    Double x = 100.1; //自动装箱

    double y = x; //自动拆箱

    System.out.println( ++ x * y);  //直接自动拆箱进行计算

  }

}

范例:以Boolean为例:

public class TestDemo{

  public static void main(String args[]){

    Boolean flag = true; //自动装箱

    uf(flag){ //自动拆箱

      System.out.println( “********”);  //直接自动拆箱

      }

  }

}

有了这种自动装箱的机制存在,就可以使用Object接收基本数据类型了

范例:利用Object接收int

public class TestDemo{

  public static void main(String args[]){

    Object obj = 10;  //

    int temp = (Integer)obj;  //向下转型为Integer,自动拆箱为int

    System.out.println(obj);  //

  }

}

Object无所不能,可接收任何类型的数据

原文地址:https://www.cnblogs.com/lonske/p/8729096.html