This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unexpected output ??

 
Rao Rekha
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That makes complete sense. Thanks Jha and Chitra.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic