ashesh shrestha ashesh shrestha - 23 days ago 6
Java Question

printing value of an integer after while causes error

I was just modifying code and I got error in the following code:

int x=1;
System.out.println("x "+x);
while (true) {
x++;

}
System.out.println ("x "+x);


The error is in the last line. Can I know what the error(error: unreachable statement) means?

Also how can I modify code such that value of x increased inside while loop doesn't change the global value and also what modification will change global value?

Answer

the while loop

while(true)

will run forever (the condition is never false) and so the code after it will never be executed.

To solve this, put the printing into the loop:

while (true){
    x++;
    System.out.println ("x "+x);
}
Comments