Reputation: 21
The code correctly prints out "x[2][2] is false", my problem is understand why this is happening. (It's correct, I just need someone to "computer speak" this logic to me- I'm taking my final in 4 hours and will never bother anyone again :) )
Thank you so much for your assistance!
public static void main(String[] args) {
boolean[][] x = new boolean[3][];
x[0] = new boolean[1];x[1] = new boolean[2];
x[2] = new boolean[3];
System.out.println("x[2][2] is " + x[2][2]);
}
Upvotes: 1
Views: 367
Reputation: 234857
When you create an array, each entry gets a default value. For boolean
, the default value is false
. (For numeric primitives, the default value is zero. For reference types, the default value is null
.)
So when you create the top-level array, boolean[][] x = new boolean[3][];
, x
is a 3-element array of boolean arrays, with each element set to the default value of null
. (A single array of primitive types is a reference type.) The program then initializes each element of x
with a new array of boolean primitives, each filled with false
elements. Note that the arrays have different lengths; this is not a problem in Java. As it happens, x[2][2]
actually exists (unlike, say, x[1][2]
), so the call to println
succeeds.
Upvotes: 3
Reputation: 6038
The default value of boolean
s in Java is false
no matter how many and how much you allocate it.
Upvotes: 0
Reputation: 115388
It is because variables of all primitive types have default value. You cannot use regular variable without initialization but when you create array each element is initialized automatically. int, long, short to 0, float and double to 0.0, boolean to false.
You do not initialize elements of your 2 dimensional array. So all its elements are false by default.
Upvotes: 0
Reputation: 88747
Array elements are initialized to their defaults which is false
in case of boolean primitives. Thus new boolean[3]
will result in {false, false, false}
;
Upvotes: 0
Reputation: 533820
When you create a new boolean[n]
all the boolean values default to false
(which is also the default for boolean
)
Upvotes: 2
Reputation: 3059
When you declare a boolean array, it automatically defaults to having all it's values 'false'.
Upvotes: 1