I am a beginner in JAVA, and have just started learning this language. I researched at How to initialize an array in Java? thread, but couldn't really find the solution.
My objective is to initialize the array at the time of declaring all the variables, and then set the values later in the program (the reason being that I want to keep my code clean i.e. I don't want to initialize and set the values at the same time.) Specifically, I am not looking to declare and set the values at the same time, but at different time.
Here's my code with different options learned from SO thread above:
public class AutoArray {
public static void main(String[] args) {
//Option 1
int[] Array1 = new int[4]; //Declare
Array1[0] = 3; //Set individual elements. Fine but repetitive.
Array1[1] = 4;
Array1[2] = 5;
Array1[3] = 6;
System.out.println("Array1 is:"+Array1);
//Option 2
int Array3[] = {3,4,5,6}; //Declare and set at the same time. Not good.
System.out.println("Array3 is:"+Array3);
//Option 3
int Array5[] = new int[3];
Array5[] = {3,5,11}; //Won't compile
}
}
As we can see above, I can either (in Option 1) set individual elements of an array using Array[i] = XYZ
where i<4
or (in Option 2) set the values at the time of declaring an array.
However, I want to do something I tried in Option 3--i.e. set the values later using curly braces. I don't want to repeat the code for setting individual elements because it looks clunky or cannot use for
loop because the values don't follow a pattern.
Is there anything I can do? I'd appreciate any thoughts.