tags:

views:

286

answers:

5

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.

+11  A: 

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).

RichieHindle
+1, With int a[] = null , b[] =null; would compile just fine
kd304
+4  A: 
int[] a = null , b[] =null;


.... it's equal to :

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

You have to do :

int[] a = null , b =null;
Matthieu
+2  A: 

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.

+1  A: 

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;
Jorn
A: 

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;
Jay R.