Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare Multiple Java Arrays on Same Line?

Tags:

java

arrays

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)

like image 333
Daniel Sopel Avatar asked Dec 01 '10 19:12

Daniel Sopel


2 Answers

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

like image 79
Gwyn Evans Avatar answered Oct 02 '22 02:10

Gwyn Evans


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.

like image 22
redcayuga Avatar answered Oct 02 '22 03:10

redcayuga