• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question ID :952739442300 JQ+

 
Greg Georges
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Lam Thai
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Hi Greg,
This URL address has the answer for the exact same question:
http://www.javaranch.com/ubb/Forum24/HTML/009781.html
Regards,
Lam
 
Elizabeth Jacob
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Greg Georges
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, have the concept down now!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic