MirroredFate
MirroredFate

Reputation: 12816

Java multiple array declaration

The statement

int[] a

is the same as

int a[]

However, what happens when you have multiple declarations in a single line?

What is the difference between

int[] a, b, c

and

int a[], b, c

Does the first one declare three arrays, and in the second they are ints, but a is an array?

EDIT:

Why does the declaration happen that way?

Is this a good reason to use the syntax int[] a rather than int a[]?

Upvotes: 1

Views: 734

Answers (6)

quazzieclodo
quazzieclodo

Reputation: 831

The other answers cover the what pretty well, but I will try to explain why that happens. Basically, the compiler interprets

XXXXXX a, b, c;

as

XXXXXX a;
XXXXXX b;
XXXXXX c;

no matter what XXXXXX is. So in your examples,

int[] a, b, c;

turns into

int[] a;
int[] b;
int[] c;

and

int a[], b, c;

turns into

int a[];
int b;
int c;

Upvotes: 2

Brandon Kindred
Brandon Kindred

Reputation: 1488

int[] a, b, c

will create 3 arrays named a, b, and c.

int a[], b, c

will create an array of integers in a, and two single integer variables b, and c.

Upvotes: 2

Cruncher
Cruncher

Reputation: 7812

static int[] a, b, c;
public static void main(String[] args){
    System.out.println(a + ", " + b + ", " + c);
}

Output: null, null, null

using static int a[], b, c;

Output: null, 0, 0

Upvotes: 1

Sadu
Sadu

Reputation: 33

int a, b, c, d, e = 4;

is declaring 5 ints but only initialising 'e'.

In the same way,

int[] a, b, c, d, e = new int[4];

will only initialise e.

You'd need something like

int[] a=new int[4], b=new int[4], etc...

which frankly, isn't worth one-lining...

Upvotes: 0

kviiri
kviiri

Reputation: 3302

The first one declares three arrays, the second one a single array and two ints. (see Java Language Specification for Java 7, §10.2)

Upvotes: 2

gla3dr
gla3dr

Reputation: 2309

from the JLS Chapter 10.2:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

For example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Upvotes: 4

Related Questions