Search code examples
javavariables

I initialize local variable, but I still get "variable might not have been initialized"


In:

int i = 10;
int j;
    
if(i == 10) {
    j = 100;
}

System.out.println(j);//error

I get an error:

variable might not have been initialized

The compiler is not smart enough to determine the value of j even though in the above line it's been explicitly defined, as int i = 10;.

I think, i is not given value during compile time, and that's why I get this initialization error.

Does int i get 10 as its value during run-time?


Solution

  • Because i is local variable, int i=10 is executed at runtime, so at compile time, compiler doesn't know that's value of i, so that the compiler cannot determine if (i==10) must be true, it can only assume the both condition. If i doesn't equal to 10, then println will use uninitialized j, that's reason why you get the error.