The main rule is that if the compiler could deduct exact value from the source code it has in the single class. Because it does all optimizations using only smallest compilation unit - class.
If I write a code
public class Test
{
private static final String i = "1";
public static void main(String[] args)
{
if(i == "2")
System.out.println("hello");
System.out.println("world");
}
}
The compiler sees all code related to the statement in this class and optimizes out the if condition. After de-compiler the code looks like
public class Test
{
private static final String i = "1";
public static void main(String[] paramArrayOfString)
{
System.out.println("world");
}
}
(I've used jd-gui)
However, if you replace ==
by the .equals
, compiler cannot assume how the method .equals
works. Because, after compilation of the Test
class, you could hack your JDK and place another version of the java.lang.String
class which returns true
for "1".equals("2")
.
So, thinking about optimization which compiler could do, first of all think how compiler could behave if any class could be recompiled later.
As another example, you could see how enum
is implemented and why does it need such "weird" way.
==
as first test already. – Syringa