📅  最后修改于: 2020-03-28 01:57:42             🧑  作者: Mango
如果我们不给数组元素赋值,而是尝试访问它们,那么编译器不会像简单变量那样产生错误。而是分配不是垃圾的值。
以下是默认分配的值。
// Java展示默认数组值
class ArrayDemo
{
public static void main(String[] args)
{
System.out.println("String 数组默认值:");
String str[] = new String[5];
for (String s : str)
System.out.print(s + " ");
System.out.println("\n\nInteger 数组默认值:");
int num[] = new int[5];
for (int val : num)
System.out.print(val + " ");
System.out.println("\n\nDouble 数组默认值:");
double dnum[] = new double[5];
for (double val : dnum)
System.out.print(val + " ");
System.out.println("\n\nBoolean 数组默认值:");
boolean bnum[] = new boolean[5];
for (boolean val : bnum)
System.out.print(val + " ");
System.out.println("\n\nReference 数组默认值:");
ArrayDemo ademo[] = new ArrayDemo[5];
for (ArrayDemo val : ademo)
System.out.print(val + " ");
}
}
输出:
String 数组默认值:
null null null null null
Integer 数组默认值:
0 0 0 0 0
Double 数组默认值:
0.0 0.0 0.0 0.0 0.0
Boolean 数组默认值:
false false false false false
Reference 数组默认值:
null null null null null