Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to initialize int array in a switch case?

How can I initialize an integer array in Java like so: int[] array = {1,2,3}; inside a switch statement?

Currently, I can write:

switch(something) {
    case 0: int[] array = {1,2,3}; break;
    default: int[] array = {3,2,1};
}

But when I try to access the array variable, eclipse will complain that it might not be initialized.

If I try to declare it like int[] array; or int[] array = new int[3]; and then have the switch statement, it would say I am trying to redeclare it.

How can I resolve this issue? Final idea is to be able to initialize an array with 10 values in just one line of code, based on some logic (a switch statement).

like image 457
Tony Bogdanov Avatar asked Jun 06 '12 21:06

Tony Bogdanov


3 Answers

Put the declaration before the switch statement. You will also need to explicitly instantiate an array of the correct type.

int[] array;
switch (something) {
    case 0: array = new int[] {1, 2, 3}; break;
    default: array = new int[] {3, 2, 1};
}
like image 171
Mark Byers Avatar answered Oct 05 '22 11:10

Mark Byers


I would tell you to put the array declaration outside the switch block, however, you cannot use = { 1, 2, 3} syntax after the declaration. You need to initialize it the regular way, as in array = new int[] {1, 2, 3};

like image 32
jn1kk Avatar answered Oct 05 '22 13:10

jn1kk


int[] array;
switch (something) {
    case 0: array = new int[]{1, 2, 3}; break;
    default: array = new int[]{3, 2, 1};
}
like image 43
GWilliams00 Avatar answered Oct 05 '22 11:10

GWilliams00