Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Java array considered two dimensional?

Tags:

java

arrays

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.

like image 888
andandandand Avatar asked Jul 18 '09 21:07

andandandand


3 Answers

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

like image 103
RichieHindle Avatar answered Oct 30 '22 16:10

RichieHindle


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


.... it's equal to :

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

You have to do :

int[] a = null , b =null;
like image 5
Matthieu Avatar answered Oct 30 '22 17:10

Matthieu


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.

like image 3
user92983 Avatar answered Oct 30 '22 17:10

user92983