8

Is it possible to initialize and/or declare multiple arrays in the same line in Java?

ie.

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

works but

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

doesn't seem to work (size of array is 4)

4 Answers 4

26

Bear in mind that

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

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

Comments

5

try

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

You have to instantiate an array for each variable if you want to create five different arrays.

If you want to create one array and reference it from five variables Goran has the solution.

Comments

4

You are missing the new keyword Try this:

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

3 Comments

Thanks, I forgot to put that in my question (edited), but it still won't compile in BlueJ (variable a may not have been initialized).
Interesting. It seems that the array object had been assigned only to reference named e.
It should be int[] a, b, c, d, e ; a = (b = (c = (d = (e = new int[4])))); The assignment operators' return value is the assigned value. However, as Jon already said, they would all still refer to the same array.. And it's two lines now.. and ugly..
2

What you tried is possible only for value types. In Java arrays are reference types i.e. objects.

What you tried is not possible (as Gwyn explained).

On the other hand you could:

int[][] arrays = new int[4][5];

And then use: arrays[0], arrays[1].. instead od a,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.