Reputation: 362
I know Java forces you to initialize every local variable before you use it. There are some cases where it gets tricky, though. Consider this:
public class TestClassOne {
public void methodOne() {
String s;
if(false)
System.err.println(s);
else
s = "Hi";
}
}
This class will compile succesfully. However, this one won't:
public class TestClassTwo {
public void methodTwo() {
String s;
if("hola".equals("chau"))
System.err.println(s);
else
s = "Hi";
}
}
Why is Java able to detect the if-block will never be entered in the first class but not in the second one?
EDIT:
Thanks for the answers.
What I'm looking for is a formal characterization of the if-condition that ensures the program will compile.
Is it then safe to conclude that this code will compile iff the if-condition is a compile-time boolean constant? At first I would have thought "no, in most cases you would get 'unreachable code' error" (except the literal false case Jesper pointed out), but I have tried the following with the given results:
if(false) ... //compiles
if(0 == 1) ... //compiles
final boolean b = false;
if(b) ... //compiles
Upvotes: 1
Views: 86
Reputation: 4274
At the JVM level, the compiler doesn't "know" anything about String equality - equals() is just another method on another class. If you replace "equals" with "someMethod", then it should be obvious why the compiler does not "know" - those runtime objects do not exist in the compiler's JVM and it is not able to call methods on them (nor would it have any assurance that the result would remain constant!)
Upvotes: 1
Reputation: 206896
if (false)
is a special case to support conditional compilation.
See Example 13.4.9-2 in the Java Language Specification and Paragraph 14.21 about unreachable statements for a detailed explanation.
Java knows that the content of the if (false)
block is never executed, so it doesn't complain about the uninitialized variable being used, but it doesn't complain with an "unreachable code" error because of the special conditional compilation case.
For method calls like equals()
, the compiler isn't going to analyze the code to see that this always returns false
in this case.
Upvotes: 5