Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.651 :

Posted: Thu Dec 11, 2014 9:51 am
by Ianyshev
Dears, explain please the next task,

class TestClass
{
public static void main(String args[])
{
boolean b = false;
int i = 1;
do
{
i++ ;
} while (b = !b);
System.out.println( i );
}
}

How 'i' gets 3 ?? Yet, (b = !b ) == true, then it should be infinite loop ...

Thanks
Dmitry

Re: About Question com.enthuware.ets.scjp.v6.2.651 :

Posted: Thu Dec 11, 2014 9:59 am
by admin
In the first iteration i is incremented to 2. Now, b = !b is executed. Here, b is false. So !b is true. Therefore, true is assigned back to b. The value of the expression b = !b is true (because true was assigned to b). So the loop will execute again. i is incremented to 3. Now, b is true. So !b is false. Therefore false is assigned back to b. The value of the expression is therefore false and the loop will terminate.
Thus i will remain 3. There is no infinite loop.