Florian Firlus
Florian Firlus

Reputation: 21

Boolean Array Issue

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

Answers (6)

Ted Hopp
Ted Hopp

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

Neigyl R. Noval
Neigyl R. Noval

Reputation: 6038

The default value of booleans in Java is false no matter how many and how much you allocate it.

Upvotes: 0

AlexR
AlexR

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

Thomas
Thomas

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

Peter Lawrey
Peter Lawrey

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

swiftcode
swiftcode

Reputation: 3059

When you declare a boolean array, it automatically defaults to having all it's values 'false'.

Upvotes: 1

Related Questions