10

Consider this code:

class arraytest {

    public static void main(String args[]) {

        int[] a = null , b[] = null;

        b = a;
        System.out.println( b );

    }

}

The line

b = a;

is flagged by the compiler saying:

Incompatible types, found int[], required int [][]

Why is b considered two dimensional? I realize the "shortcut" declaration

int[] a = null , b[] = null;

is to blame, but why does it make the array two dimensional when only one set of brackets have been written? I find this syntax unclear and obfuscating.

5 Answers 5

19

Take this example:

int a, b;

Then both a and b are ints, right? So now take this:

int[] a, b;

The both a and b are int arrays. So by adding another set of brackets:

int[] a, b[];

you have added another set of brackets to b.

Either of these would be fine:

int[] a = null , b = null;
int a[] = null , b[] = null;

or as you say, simply putting them on separate lines would work too (and be much easier to read).

Sign up to request clarification or add additional context in comments.

Comments

5
int[] a = null , b[] =null;


.... it's equal to :

int[] a = null;
int[][]b = null;

You have to do :

int[] a = null , b =null;

Comments

3

In addition to the other answers, Java does not have multi-dimensional arrays. Java has arrays of any type. This "any type" may itself be an array. Multi-dimensional arrays are distinctly different, although subtly.

Comments

2

If you take out the a declaration, this is what you have:

int[] b[] = null;

which is, unfortunately, a legal alternative to

int[][] b = null;

Comments

1

I was lead to believe that the syntax of allowing the [] after the b was there solely for the C-language crowd who would feel more at home with it. Unfortunately, it has the side effect of allowing confusing declarations like

 int[] b[];

which ends up the same as

 int[][] b;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.