实例变量会有默认初始值(0,false,null,'\u0000'等),局部变量不会有默认初始值,
public class test01 {
private String s;
private int [] year = new int[3];
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public int[] getYear() {
return year;
}
public void setYear(int[] year) {
this.year = year;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
test01 t = new test01();
for(int i=0;i<3;i++)
System.out.println("year[" + i + "] = " + t.getYear()[i]); //代码A
int[] year2 = new int[3];
for(int i=0;i<3;i++)
System.out.println("year2[" + i + "] = " + year2[i]); //代码B
if (t.getS() == null){ //代码C
<span style="white-space:pre"> </span>System.out.println("s is null");
}
String s2;
if (s2 == null){ //代码D
System.out.println("s is null");
}
}
}
代码A处能正常运行,year为实例变量,默认数组内元素都为0:
year[0] = 0
year[1] = 0
year[2] = 0
代码B处能正常运行,因为year2已被初始化,虽然内部元素没有初始化,但都默认为0,内部元素的初始化跟是否是实例变量还是局部变量无关:
year2[0] = 0
year2[1] = 0
year2[2] = 0
代码C处能正常运行,s为String即为对象,默认值为null:
s is null
代码D处有编译错误,S2为局部变量,不会有任何默认值,也不是null值:
The local variable s2 may not have been initialized