javaif-statement

Unreachable code in if-else structure


If have the following code I correctly get an warning in eclipse at the else if code :

final int x = 8;
if (x < 10) {
    System.out.println(x);
} else if (x < 5) {
    System.out.println(x);
}

But I don't get any warning if I replace the line

final int x = 8;

with

final int x = getX();

getX() is defined somewhere.

What is the reason for this?


Solution

  • JVM knows that x always would be less than 10 in compile-time, but if you replace x declaration

    final int x = getX();
    

    JVM will know x value to compare only in runtime

    Related questions: