Can someone please explain the logic of this question, cannot seem to grasp the idea What will be the result of attempting to compile and run the following program? class TestClass { public static void main(String args[]) { boolean b = false; int i = 1; do { i++ ; } while (b = !b); System.out.println( i ); } } The answer is that it will print 3. Guess that (b = !b) evaluates to (false = true), so therefore we go through another iteration because the condition is true, then I suppose it becomes (true = false) and exit the loop. Is this the correct reasoning?
<b>Greg Georges</b><br /><i>Sun Certified Java Programmer for the Java2 platform (SCJP)</i><br /><i>Sun Certified Java Developer for the Java2 platform (SCJD)</i>
Lam Thai
Ranch Hand
Joined: Apr 02, 2001
Posts: 117
posted
0
Originally posted by Greg Georges: Can someone please explain the logic of this question, cannot seem to grasp the idea What will be the result of attempting to compile and run the following program? class TestClass { public static void main(String args[]) { boolean b = false; int i = 1; do { i++ ; } while (b = !b); System.out.println( i ); } } The answer is that it will print 3. Guess that (b = !b) evaluates to (false = true), so therefore we go through another iteration because the condition is true, then I suppose it becomes (true = false) and exit the loop. Is this the correct reasoning?
the while statement is like this: while(b=!b) where it is an assignment statement and not a shallow comparison '=='. so after the first iteration i is 2 and the while condition becomes b = true. the value of i = 3 in the next iteration and then the while condition becomes b = false and the do loop exits and prints the value of i as 3. Elizabeth