wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Unexpected output ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Unexpected output ??" Watch "Unexpected output ??" New topic
Author

Unexpected output ??

Rao Rekha
Greenhorn

Joined: Jul 29, 2002
Posts: 11
Could anyone kindly let me know why does the following code prints 3 ?
class TestClass
{
public static void main(String args[])
{
boolean b = false;
int i = 1;
do
{
i++ ;
} while (b = !b);
System.out.println( i );
}
}
Thanks in advance.
Gautam Jha
Greenhorn

Joined: Sep 23, 2002
Posts: 10
Because of "(b = !b)" in the "while" statement.
Note its an assignment and not an check. After
the assignment, the value of b is used to determine whether to quit the loop or not? Make sense??
Chitra Jay
Ranch Hand

Joined: May 02, 2002
Posts: 76

do-while loop executes its body atleast once irrespective of whether the condition returns true/false
i gets incremented to 2
goes thru the condition in while
b= !b
in this statement,! has higher precedence than =.
!b evaluates to !false ==> true
now b gets assigned the value true.
(b = (!false)) -> true
since the condition returns true,it enters the loop again,and increments i to 3.
Now,the condition is evaluated once again,
but returns false (because b = (!true) )therefore comes out of the loop and prints 3.
Chitra
Rao Rekha
Greenhorn

Joined: Jul 29, 2002
Posts: 11
That makes complete sense. Thanks Jha and Chitra.
 
GeeCON Prague 2014
 
subject: Unexpected output ??