Search code examples
javafinal

java final keyword causes error: unreachable statement. why is it not printing hello world


error: unreachable statement

why is it not printing hello world?

public class Main
{
    public static void main(String[] args) {
        final int a=10,b=20;
        while(a>b){
            System.out.print("Message");
        }
        System.out.println("Hello World");
    }
}

Solution

  • The a>b in your code is a so-called constant expression because a and b are final and assigned with a literal value (same would apply if it would have been assigned with another constant expression). The Java compiler evaluates these constant expressions during compilation. Because it evaluates to false, it decides that the while loop will never be executed, and thus the content of the loop is an "unreachable statement", and compilation fails with an error.

    It never prints "Hello World", because compilation fails, so the code is never run. Printing happens at run time, not compile time.