Most compiler optimize code using optimization algorithm which are rely on heuristics(experience-based techniques) and approximations. The below code would come into control flow analysis.
I ran a lot of samples of the program
Case A) if-else with final variable - Compiler throws a warning Dead Code. The generated byte code does not have any if-else statement.
public static void main(java.lang.String[])
Stack=1, Locals=2, Args_size=1
0: iconst_0
1: istore_1
2: return
LineNumberTable:
line 42: 0
line 54: 2
LocalVariableTable:
Start Length Slot Name Signature
0 3 0 args [Ljava/lang/String;
2 1 1 selection I
}
Case B) if-else without final variable - No compiler error but no code optimization too.
final int selection i=100; //case A
//int selection i=100; //case B
if(selection==1){
System.out.println("Hi");
}else if(selection==2){
}else{
}
Case C) if-else with final variable but if-else statement is put in another method say
computeIfLese(int selection)
- No code OPtimization done since this method can be invoked by other instance with different value of parameter ( Obviously).
Since the compiler optimization technique is based on heuristics , there would have been this case as a miss but who would think of the rarest of rarest case.
Comments from the Java Gods awaited... :)
Here is a living proof that Compiler has not optimized this.Check label 5:
public static void main(java.lang.String[]);
Code:
Stack=2, Locals=2, Args_size=1
0: bipush 100
2: istore_1
3: bipush 100
5: lookupswitch{ //2
200: 32;
300: 40;
default: 48 }
32: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
35: ldc #22; //String 200
37: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
40: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream;
43: ldc #30; //String 300
45: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
48: return
LineNumberTable:
line 11: 0
line 15: 3
line 17: 32
line 18: 40
line 21: 48
LocalVariableTable:
Start Length Slot Name Signature
0 49 0 args [Ljava/lang/String;
3 46 1 selection I
StackMapTable: number_of_entries = 3
frame_type = 252 /* append */
offset_delta = 32
locals = [ int ]
frame_type = 7 /* same */
frame_type = 7 /* same */
}
switchisn't reassigning any values. - Jeel Shah