简体   繁体   中英

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

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.

它显示无法到达的原因,因为xy都被声明为final ,它们无法改变(它们是常量),因此while将始终循环,并且永远不会达到“Hi”打印

Java knows that final variables cannot be changed. You've declared x,y to both be final. Therefore it knows that the loop cannot terminate, because x < y is always true.

This is because in your example the final variables are initialized with a compile-time constant expression . making them constant variables, the compiler knows it can never be changed during run time. Thus final int x =10, y=20 become constant variables known from the compile time.

which is equivalent to :

  while (10<20){
         System.out.println("Hello");
     }
  System.out.println("Hi");

Now the compile time evaluation tells that the statement System.out.println("Hi"); will be unreachable in this case.

where as non constant variables can be changed during run time. So no compile time check for the while condition.

for more ref: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM