Search code examples
javavariableslocalfinal

Why java final variable showing unreachable Statement


class Temp
{
    public static void main(String[] args)
    {
         int x=10,y=20;
        while (x<y)
        {
            System.out.println("Hello");
        }
        System.out.println("Hi");
    }
}

output it prints Hello infinity times

but when i make local variable final int x=10,y=20; then it is showing Statement Unreachable


Solution

  • Making those variables final also makes them constant variables. That means the compiler can replace the use of the variables with the value they are initialized with.

    As such, the compiler attempts to produce the following

    while (10 < 20)
    

    This is equivalent to

    while (true)
    

    That will make it an infinite loop and the code that comes after the block will become unreachable.

    This is specified in the Java Language Specification, here

    A while statement can complete normally iff at least one of the following is true:

    • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

    • There is a reachable break statement that exits the while statement.

    None of those is satisfied, so the while statement cannot complete normally. Everything after it is unreachable.