整数的局部变量数组默认为零
Local variable array of ints defaults to zero
为什么当 'ints' 的数组作为局部变量时它们默认为零?
public static void main(String [] args) {
int []arrayInts = new int[5];
for(int i: arrayInts)
System.out.println(i);
//Prints out zeros
}
虽然 'int' 变量被声明为局部变量,但它不会被初始化。
public static void main(String [] args) {
int a;
System.out.println(a);
//Compilation error: The local variable a may not have been initialized
}
这两个例子没有可比性。
在第一个中,您正在主动初始化您的数组。 The default value 对于整数数组是 0。
在第二个示例中,您 未 显式或隐式初始化变量 a
,并且您'试图利用它。 Java 会投诉此操作。
为什么当 'ints' 的数组作为局部变量时它们默认为零?
public static void main(String [] args) {
int []arrayInts = new int[5];
for(int i: arrayInts)
System.out.println(i);
//Prints out zeros
}
虽然 'int' 变量被声明为局部变量,但它不会被初始化。
public static void main(String [] args) {
int a;
System.out.println(a);
//Compilation error: The local variable a may not have been initialized
}
这两个例子没有可比性。
在第一个中,您正在主动初始化您的数组。 The default value 对于整数数组是 0。
在第二个示例中,您 未 显式或隐式初始化变量 a
,并且您'试图利用它。 Java 会投诉此操作。