Inconsistent initialization? Why is it that when I forget to initialize a variable the compiler gives me the "variable myVar might not have been initialized" error message and sometimes it doesn't?

Alessandro A. Garbagnati

The compiler gives you that error message every time you are using a local variable without an explicit initialization in the code that precedes that call. For example, declaring a variable inside a method and assigning the value in a switch block, without the default case:

String myVar;
switch (anotherVar) {

    case 0:
      myVar = "zero";

    case 1:
      myVar = "positive";

    case -1:
      myVar = "negative";

In this example, you know that your switch case is covering all the possible cases, but the compiler doesn't. The switch case block, from the compiler 'point of view', is missing the default case, so it's incomplete, and there is the possibility that your variable it's not initialized.

But, as pointed out, this message doesn't appears every time you don't initialize a variable. If you want to try, just use the same code, but move the declaration "String myVar" outside the method: you will not get that message again.

The reason of this behaviour is that the compiler assign a defualt value to all the members of a class. The default value it's normally '0' for all numeric type, 'false' for boolean and 'null' for Objects. So, for example, when you put in your code a declaration of instance variables:

int x;
boolean bool;
String y;
MyClass myClass;

the compiler will translate this in something like this:

int x = 0;
boolean bool = false;
String y = null;
MyClass myClass = null;

This gives also an interesting additional hint:
When an object it's created all the instance variables of the class are initialized with their default value. This happens indipendently if the declaration contains or not the first assignment. Then, before executing the constructor, the initialization is done and, finally, the body of the constructor it's executed. This meand that if in the code there is:
  String myObject = null;
it will be translated in:
  String myObject = null; (at the creation of the object)
  myObject = null; (instance initialization)
resulting in a double initialization.

Somebody can argue that this overhead it's minor, few additional lines of bytecode, but if the Class it's created many times, it could result in an extra overhead that can be easilty avoided. The rule should be to explicitly initialize the instance variables only when the value to assign it's different from the default.