Advertisement

Udemy WW Udemy WW

Tuesday, 20 December 2011

Infinite while loop in Java


In The following infinite while loop in Java. It will give compile-time error .
while(true)
{
     System.out.println("hello...");
}

System.out.println("End of while"); //Unreachable statement - compiler-error.

The following same infinite while loop, however works and does not gives any errors in which I just replaced the condition with a boolean variable.
boolean v=true;

while(v)
{
     System.out.println("hello..");
}

System.out.println("End Of While"); //No error here.

In the second case also, the statement after the loop is obviously unreachable because the boolean variable v is true still the compiler doesn not gives any error. Why?
Ans:
The first Statement always result in an infinite loop because we have specify a constant in condition of while loop, where as in second case compiler assume that, there is possibility of change of value of v inside loop.

No comments:

Post a Comment

Advertisement

Udemy WW