Most modern Java compilers have optimizers that can detect simple cases when it is logically impossible for certain statements in a program to ever be executed. In such cases, the compiler warns the programmer about the useless code. Write a short Java method that contains code for which it is provably impossible for that code to ever be executed, yet the Java compiler does not detect this fact
package Data_Structures.Chapter2;
public class DeadCode {
// this method has unreachable code and gives compilation error if we uncomment the println statement
public void thisMethodHasUnreachableCode() {
System.out.println("Reachable code");
return;
// below line cause compilation problem as it is unreachable code
// System.out.println("Unreachable code");
}
// below method has deadcode it wont cause compilation error, but gives waring
public void thisMethodHasDeadCode() {
System.out.println("Reachable code");
if (2 < 3) {
return;
}
System.out.println("Dead Code");
}
// this method too has unreachable code and gives compilation error if we uncomment the println statement
public void thisOneHasUnreachableCode() {
System.out.println("Reachable code");
while (1 < 2) {
return;
}
// System.out.println("Again unreachable code");
}
public static void main(String args[]) {
DeadCode deadcode = new DeadCode();
deadcode.thisMethodHasUnreachableCode();
deadcode.thisMethodHasDeadCode();
deadcode.thisOneHasUnreachableCode();
}
}
Output:
Reachable code
Reachable code
Reachable code