int a = 1, b;
if(a > 0) b = 1;
if(a <= 0) b = 2;
System.out.println(b);
If I run this, I receive:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable b may not have been initialized at Broom.main(Broom.java:9)
I know that the local variables are not initialized and is your duty to do this, but in this case, the first if doesn't initialize the variable?
Java compiler cannot find out that the other
if
works as anelse
. Compilers are smart but not that smart.Local variables are not replaced in compile time so the compiler have no idea if the
IF
is true or false.On the other hand if the variable was defined
final
then it will be replaced during compile time.Please don't try to run your code when it doesn't even compile.
Usually you couldn't do that anyway, but modern IDEs are so "helpful" to allow you to do that. They usually replace uncompilable parts of the code with code that just throws an error such as the one you see.
The much better approach is to look at the error messages your compiler/IDE gives you and try to fix those before you try to run your application.
Learning the difference between compiler errors and runtime exceptions is an important step to take.
If you change the second
if
toelse
, then the compiler would be happy.If you really want to go deep into this matter, one whole chapter of the Java Language Specification is dedicated to the issue of Definite Assignment. This case pertains to your specific example:
This particular example (and many other illustrative ones) may seem to defy your expectation, but this is exactly the way the language designers wanted it, and all compilers must abide by the rules.
Focus on "IF", The compiler can't tell if the condition will be true.
You could add the
final
keyword to the declaration ofa
to help your compiler optimizing the code.