public class test {
public static void main(String[] args) {
int MAX = 5;
boolean bit[] = new boolean[MAX];
float[] value = new float[2*3];
int[] number = {10, 9, 8, 7, 6};
System.out.println(bit[0]); // prints “false”
System.out.println(value[3]); // prints “0.0”
System.out.println(number[1]); // prints “9”
}
}
I’m testing out the above code, how come Java would initialize the values for you? I thought it should throw compilation error if I don’t initialize my variables. Also, what should I do to the line float[] value = new float[2*3]; if I want to initialize them all to 0.0?
Static and instance variables, and elements of arrays are initialized to default values (0, false,
'\0', null etc). Local variables aren’t initialized by default.In your code, only the array elements aren’t explicitly initialized – the compiler would have a hard time working out whether every array element you tried to use was initialized. What would you expect to happen if the array came from a parameter, for example?
From the Java Language Specification, section 15.10.1:
(That’s the situation you’re in – DimExpr is your 3 * 2 expression here.)