LocalVariablesAutoInitialized

Misconception:

Local variables get initialized to their default values if we do not explicitly initialize them.

Incorrect

Local variables are automatically initialized

Correct

Local variables must be initialized explicitly

Correction
Here is what's right.

In Java, all local variables have to be explicitly initialized before they can be used.

class C {
  void m() {
    int a;       // declare, but don't initialize
    int b;       // declare, but don't initialize
    int c = 42;  // declare and initialize

    b = 19;      // set to value, now initialized

    use(a);      // ERROR: cannot use a, not yet initialized
    use(b);      // OK
    use(c);      // OK
  }
}

Value
How can you build on this misconception?

This misconception provides an opportunity to explain why some kinds of variables are automatically initialized to default values, but other kinds of variables are not.

The reason local variables are not automatically initialized is the performance cost of doing so. Local variables live in stack frames (activation records).

On the other hand, in Java, instance variables are automatically initialized (to the default value of their type). Instance variables live in heap objects.

Heap objects can relatively cheaply be allocated in memory regions that were set to zero. Thus the runtime environment can guarantee that all their instance variables are zeroed out (conveniently the default values of Java types are represented as 0 in binary).

Stack frames, on the other hand, have to be allocated on the stack, where just a short moment before other stack frames (with variables holding possibly non-zero values) had been located. Zeroing the stack frame at each call or return of a method would incur a significant cost, and thus the language specification requires local variables to be explicitly initialized.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.