Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 602
Debabrata Avatar asked May 08 '26 17:05

Debabrata


1 Answers

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.

like image 90
Sotirios Delimanolis Avatar answered May 10 '26 07:05

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!