[Q#10922489][A#10922519] Java: How to initialize int array in a switch case?
https://stackoverflow.com/q/10922489
How can I initialize an integer array in Java like so: int[] array = {1,2,3}; inside a switch statement? Currently, I can write: 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).
Answer
https://stackoverflow.com/a/10922519
Put the declaration before the switch statement. You will also need to explicitly instantiate an array of the correct type.
APIzation
int[] array;
switch (something) {
case 0: array = new int[] {1, 2, 3}; break;
default: array = new int[] {3, 2, 1};
}
package com.stackoverflow.api;
public class Human10922519 {
public static int[] arrayInSwitchCase(int something) {
int[] array;
switch (something) {
case 0:
array = new int[] { 1, 2, 3 };
break;
default:
array = new int[] { 3, 2, 1 };
}
return array;
}
}
package com.stackoverflow.api;
/**
* Java: How to initialize int array in a switch case?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/10922519">https://stackoverflow.com/a/10922519</a>
*/
public class APIzator10922519 {
public static void java(int something) throws Exception {
int[] array;
switch (something) {
case 0:
array = new int[] { 1, 2, 3 };
break;
default:
array = new int[] { 3, 2, 1 };
}
}
}