4

Why the final java variable indicating the inaccessible state

 3 years ago
source link: https://www.codesd.com/item/why-the-final-java-variable-indicating-the-inaccessible-state.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why the final java variable indicating the inaccessible state

advertisements
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK