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
       }       
Jeremy Levett
  • 939
  • 9
  • 13
  • https://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java – whatamidoingwithmylife Dec 07 '17 at 22:08
  • 2
    Because it's in the Java specification that it arrays get initialized with zero. Local variables are not (fields are). – daniu Dec 07 '17 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. – markspace Dec 07 '17 at 22:10
  • 1
    Think of array values as member variables on the array object, which always have a default value. – shmosel Dec 07 '17 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. – George Dec 07 '17 at 22:22

1 Answers1

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 1
    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 Dec 07 '17 at 22:12
  • @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. – Makoto Dec 07 '17 at 22:14