//创建数值为80的Integer对象
Integer objInt = new Integer(80);
//创建数值为80.0的Double对象
Double objDouble =new Double(80.0);
//算数运算
double sum =objInt + objDouble;
注意以上算数运算在Java 5 之前有编译错误
包装类对象转换为基本数据类型,这个过程发生了拆箱(unboxing)过程。
相反的操作,基本数据类型自动转换为包装类对象,这个过程发生了自动装箱(autoboxing)过程。
代码案例如下:
public static void main(String[] args) {
Integer objInt = new Integer(80);
Double objDouble = new Double(80.0);
//自动拆箱
double sum = objInt + objDouble;
//自动装箱
//自动装箱‘C’转换为Character对象
//Character objChar='C';
char objChar='C';
//自动装箱true转换为Boolean对象
//Boolean objBoolean=true;
boolean objBoolean=true;
//自动装箱80.0f转换为Float对象
Float objFloat=80.0f;
//自动装箱100转换为Integer对象
display(100);
//避免出现下面的情况
Integer obj =null;
int intVar = obj; //运行期异常NullPointerException
}
/**
*
* @param objInt Integer对象
* @return int数值
*/
private static int display(Integer objInt) {
System.out.println(objInt);
//return objInt.intValue();
//自动拆箱Integer对象转换为int
return objInt;
}
扫描二维码关注公众号,回复:
9692934 查看本文章