变量和数据类型:
https://blog.csdn.net/Mr_zhang66/article/details/107768673
在本文提到,Java的数据类型分两种:
基本类型:byte,short,int,long,boolean,float,double,char
引用类型:所有class和interface类型
引用类型可以赋值为null,表示空,但基本类型不能赋值为null:
String s = null;//正确
int n = null; // compile error!
那么,如何把一个基本类型视为对象(引用类型)?
比如,想要把int基本类型变成一个引用类型,我们可以定义一个Integer类,它只包含一个实例字段int,这样,Integer类就可以视为int的包装类(Wrapper Class):
public class Integer {
private int value;
public Integer(int value) {
this.value = value;
}
public int intValue() {
return this.value;
}
}
定义好了Integer类,我们就可以把int和Integer互相转换:
Integer n = null;
Integer n2 = new Integer(99);
int n3 = n2.intValue();
int和Integer可以互相转换:
int i = 100;
Integer n = Integer.valueOf(i);
int x = n.intValue();
所以,Java编译器可以帮助我们自动在int和Integer之间转型:
Integer n = 100; // 编译器自动使用Integer.valueOf(int) int x = n; // 编译器自动使用Integer.intValue()
这种直接把int变为Integer的赋值写法,称为自动装箱(Auto Boxing),反过来,把Integer变为int的赋值写法,称为自动拆箱(Auto Unboxing)。
对两个Integer实例进行比较要特别注意:绝对不能用==比较,因为Integer是引用类型,必须使用equals()比较:
我们把能创建“新”对象的静态方法称为静态工厂方法。创建新对象时,优先选用静态工厂方法而不是new操作符。
在我们自己创建Integer的时候,以下两种方法:
方法1:Integer n = new Integer(100);
方法2:Integer n = Integer.valueOf(100);