/**
* 包装类
* 包装类是为了解决基本类型不能在直接参与面向
* 对象开发的问题.
* 8个基本类型对应8个不同的包装类,其中6个表示
* 数字的包装类继承自java.lang.Number,其他两
* 个继承自Object
* @author ta
*
*/
public class IntegerDemo1 {
public static void main(String[] args) {
int d = 128;
// Integer i1 = new Integer(d);
// Integer i2 = new Integer(d);
/*
* java推荐我们使用包装类的静态方法:
* valueOf来将基本类型转换为包装类
*/
Integer i1 = Integer.valueOf(d);
Integer i2 = Integer.valueOf(d);
System.out.println(i1==i2);//false
System.out.println(i1.equals(i2));//true
//包装类转换为基本类型
int i = i1.intValue();
System.out.println(i);
double dou = i1.doubleValue();
System.out.println(dou);
long lon = i1.longValue();
System.out.println(lon);
byte b = i1.byteValue();
System.out.println(b);
}
}
/**
* 数字类型的包装类有两个常量:
* MAX_VALUE,MIN_VALUE分别记录了其对应的基本
* 类型的取值范围
* @author ta
*
*/
public class IntegerDemo2 {
public static void main(String[] args) {
int imax = Integer.MAX_VALUE;
System.out.println(imax);
int imin = Integer.MIN_VALUE;
System.out.println(imin);
long lmax = Long.MAX_VALUE;
System.out.println(lmax);
long lmin = Long.MIN_VALUE;
System.out.println(lmin);
/*
* 包装类提供了一个功能,静态方法:parseXXX
* 该方法可以将字符串解析为对应的基本类型
* 数据,前提是该字符串能正确描述要转换的
* 基本类型可以保存的值.
*/
String str = "123";
int a = Integer.parseInt(str);
double dou = Double.parseDouble(str);
System.out.println(a);//123
System.out.println(dou);//123.123
}
}
/**
* JDK5之后推出了一个新的特性:自动拆装箱
* 该特性是编译器认可的,而不是虚拟机.
* 编译器在看到有基本类型与包装类之间互相赋值
* 时会添加转换代码将他们转换.
* @author ta
*
*/
public class IntegerDemo3 {
public static void main(String[] args) {
/*
* 这里触发了编译器的自动拆箱特性
* 代码会被编译器改为:
* int i = new Integer(1).intValue();
*/
int i = new Integer(1);
/*
* 触发自动装箱特性,代码会被改为:
* Integer in = Integer.valueOf(i);
*/
Integer in = i;
}
}