Java中的默认数组值
如果我们不给数组元素赋值并尝试访问它们,编译器不会像简单变量那样产生错误。相反,它分配的值不是垃圾。
以下是默认分配的值。S. No. Datatype Default Value 1 boolean false 2 int 0 3 double 0.0 4 String null 5 User-Defined Type null
例子:
Java
// Java program to demonstrate default
// values of array elements
class ArrayDemo {
public static void main(String[] args)
{
System.out.println("String array default values:");
String str[] = new String[5];
for (String s : str)
System.out.print(s + " ");
System.out.println(
"\n\nInteger array default values:");
int num[] = new int[5];
for (int val : num)
System.out.print(val + " ");
System.out.println(
"\n\nDouble array default values:");
double dnum[] = new double[5];
for (double val : dnum)
System.out.print(val + " ");
System.out.println(
"\n\nBoolean array default values:");
boolean bnum[] = new boolean[5];
for (boolean val : bnum)
System.out.print(val + " ");
System.out.println(
"\n\nReference Array default values:");
ArrayDemo ademo[] = new ArrayDemo[5];
for (ArrayDemo val : ademo)
System.out.print(val + " ");
}
}
输出
String array default values:
null null null null null
Integer array default values:
0 0 0 0 0
Double array default values:
0.0 0.0 0.0 0.0 0.0
Boolean array default values:
false false false false false
Reference Array default values:
null null null null null