1

Why is it that when an array of 'ints' is made as a local variable they default to zero?

       public static void main(String [] args) {
           int []arrayInts = new int[5];
           for(int i: arrayInts)
                System.out.println(i);
           //Prints out zeros 
       }

While if an 'int' variable is declared as a local variable it does not get initialized.

       public static void main(String [] args) {            
           int a;
            System.out.println(a);
           //Compilation error: The local variable a may not have been initialized
       }       
5
  • stackoverflow.com/questions/415687/… Commented Dec 7, 2017 at 22:08
  • 2
    Because it's in the Java specification that it arrays get initialized with zero. Local variables are not (fields are). Commented Dec 7, 2017 at 22:09
  • 1
    Right-o. Basically because "that's how it works." Slightly more detail: because the Java spec says so. Local variables are always uninitialized, and arrays created with new are always initialized. Java is 100% consistent in that regard. Commented Dec 7, 2017 at 22:10
  • 1
    Think of array values as member variables on the array object, which always have a default value. Commented Dec 7, 2017 at 22:14
  • 2
    Short answer is that the new keyword initialises all objects created with it by default. "Stack" allocated objects are not initialised by default because the compiler can check at compile time if there's a danger of you using a stack variable before it's initialised, the same is not true of variables whose memory is dynamically allocated. Commented Dec 7, 2017 at 22:22

1 Answer 1

2

These two examples aren't comparable.

In the first one, you are actively initializing your array. The default value for an array of ints is 0.

In the second example, you've not initialized the variable a, either explicitly or implicitly, and you're attempting to make use of it. Java will complain about this action.

Sign up to request clarification or add additional context in comments.

2 Comments

Right. The examples might seem comparable to someone new, but they aren't. new is special and does things, like initialize arrays, that a plain local variable doesn't. It's a big difference even if it's only one little keyword.
@markspace: You overlooked something important: the assignment operator. You can new things up in an application all day without ever assigning it to a variable. You can declare variables without assigning values to them. But if you try to use a variable that hasn't been assigned with some value, you're going to have a compilation error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.