ashesh shrestha ashesh shrestha - 5 months ago 23
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) {

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?


the while loop


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){
    System.out.println ("x "+x);