Originally posted by ratul banji:
Hi all,
class TestClass
{
public static void main(String args[ ] )
{
boolean b = false ;
int i = 1 ;
do
{
i++ ;
} while (b = !b) ;
System.out.println( i ) ;
}
}
//o/p=3
Unlike the while(){ } loop, the do {} while() loop executes atleast once and the condition is checked after the interation.The o/p shows that this loop is executing twice BUT how ?Pls..some1 explain it 2 me.
( Note that.. it is given 'b=!b' not 'b==!b')
THANKS IN ADVANCE.
Ratul Banerjee.
Hi Ratul,
You are right that the (do {} while) loop executes atleast once. So the first time, i++ inside the loop will yield 2.
Now while (b = !b) would be equivalent to while (b = !false) so b will true. (while(true)) will cause the loop to execute again.
This time i++ will yield a value of 3. Now come the while statement again. It will be evaluated as (b = !true) this time. So b will be false and that terminates the loop and i will retains the value of 3.
Hope that helps,
Lam