Variable x might not have been initialized error

I just do not see why this isn't working:

public class HelloWorld {
    public static void main(String []args) {
        int a = 9;
        boolean isOdd;

        if (a != 0) {
            isOdd = false;
        } else if (a == 0) {
            isOdd = true;
        }

        if (isOdd == false) {
            System.out.print("Boolean is false"); 
        }
    }
}

HelloWorld.java:15: error: variable isOdd might not have been initialized

if (isOdd == false) {
    ^

Jon Skeet
people
quotationmark

The compiler doesn't consider a != 0 and a == 0 to be mutually exclusive conditions - or rather, it doesn't look at whether two if conditions are mutually exclusive to work out what happens. So you can fix the error by changing your code to:

if(a != 0) {
  isOdd = false;
} else {
  isOdd = true;
}

At which point you'd be better off writing:

boolean isOdd = a == 0;

Which isn't a good test for oddness, but it would at least compile...

Basically, whenever you get a message like this, it means there's some way through your code that the compiler thinks might be plausible, but which doesn't initialize the variable. You've got:

if (condition1) {
    // Initialize variable
} else if (condition2) {
    // Initialize variable
}

So if neither condition1 nor condition2 is true, the variable won't be initialized. The only way in which the compiler really cares about the conditions here is if either evaluating the condition initializes the variable, or of the condition is a compile-time constant expression (in which case it can assume that that branch either is or isn't taken, depending on the value of that constant expression).

people

See more on this question at Stackoverflow