0

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.

Community
  • 1
  • 1
watchtower
  • 4,140
  • 14
  • 50
  • 92
  • Where did you get the idea that declaring and initializing variables at the same time isn't clean code? Keeping everything in one place is as clean as you can get. – Kevin Krumwiede Dec 30 '16 at 03:44
  • @Kevin Krumwiede - Thanks for your question. I believe it isn't clean because let's say that you have 50ish variables, and you have created a function in a different file (I have transitioned from C to Java so I don't the equivalent of function or method in JAVA) to declare these variables. I think it will be not a good experience for code reviewer to go back and forth between declaration piece and usage (setting) piece. Right? I'm new to JAVA world, so I am not sure the best way to handle this. I'd appreciate your thoughts. – watchtower Dec 30 '16 at 03:47
  • @watchtower start writing code and you will know what you were worrying is rarely a real problem. In your case, you should simply declare+initialize the local variable at the spot it is used. What you were trying to do usually creates hard-to-review code instead – Adrian Shum Dec 30 '16 at 03:55
  • This discussion isn't very suitable for comments, but in short, variables should have the narrowest scope possible. For example, if they're only used in one method, then they should be declared and initialized inside that method. If they're only used in one class, they should be `private` members of the class. Et cetera. In every case, it's easier to review and maintain if they're initialized close to where they're declared. – Kevin Krumwiede Dec 30 '16 at 04:00
  • @Kevin Krumwiede--You are spot on. The array that I am going to use above is neither declared nor used in one class, method. It's a global level variable that would be utilized by different classes and later their values will be set as per need--sometimes prime numbers, sometimes Fibonacci series etc.. I thought of clarifying this. If you want, I can add this above so that the readers get one more reason for what I want. – watchtower Dec 30 '16 at 04:09
  • Why are you reusing the array for different purposes? That sounds extremely confusing and bug-prone. If you're worried about wasting memory with multiple arrays, that's almost certainly premature optimization. – Kevin Krumwiede Dec 30 '16 at 04:41
  • @Kevin - as you said, it's because of not using multiple arrays, and not creating multiple arrays, something like global variable. – watchtower Dec 30 '16 at 05:00

2 Answers2

3

Arrays have a fixed size, so you'll be creating a new array when you do this later (that is, your initial value can be null). Next, you are looking at syntatic sugar here

int Array3[] = { 3, 4, 5, 6 };

is equivalent to (and the shorter form is only allowed at declaration)

int Array3[] = new int[] { 3, 4, 5, 6 };

So, you can do

int Array5[] = null;
Array5 = new int[] { 3, 5, 11 };
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • It's almost always a bad idea to initialize a variable to `null`. For most cases, it unnecessarily introduces the possibility of `NullPointerException`s, it keeps the compiler from being able to tell you at compile time when you're mistakenly using uninitialized variables so that you can fix that problem earlier, and it adds ugliness. – Chai T. Rex Dec 30 '16 at 23:08
-2
//Option 3
int Array5[] = new int[3];//Array5 to be an object.
Array5[] = {3,5,11}; //after this ,Array5 become another object.
//'{3,5,11}' means 'new int[]{3,5,11}'
sam
  • 1
  • 1
  • That code doesn't compile, and even if you correct the syntax, it throws away the original `new int[3]` object when you use another `new int[] { 3, 5, 11 }`, so you might as well have not initialized it in the first place. – Chai T. Rex Dec 30 '16 at 23:11