Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain??

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question ID :952739442300
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 );
}
}

Ans : It will print 3..
WHY??
Sonir
 
Jim Hall
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Before the loop variable i = 1, b = false. The first time through the do loop i is incremented to 2. At the end of the loop b is set to true (!b). Next loop iteration i becomes 3. Now b is set to false (!b) so loop ends.
Sonir can you please be more descriptive in your choice of topic headings. Please explain?? What's the Output? are not very helpful.
But most important please put your code in BBCode blocks for easier reading.
 
mario jones
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is meant by BBCode blocks?
Sorry if this is an elementary question. I just haven't heard any coding standard referred as BBCode.
thanx in advance.
Mario
 
Jim Hall
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you post a message there are tags which allow you place code within the page. It will use a monospaced font and retain indentation making it much easier to read.

Quote here...

There are buttons which insert the tags for you.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question seems to be testing understanding of the difference between the assignment operator '=' and the equality operator '=='.
If the while() test had been
this would always return false.
However,
is an assignment statement. b gets the value of (NOT b). The first time through the loop, b is false, so (NOT b) is true; b gets assigned the value 'true'. ALSO, the value of the expression in the while() clause is evalutated and is the value of b, which is true, so the test succeeds and the loop runs again.
Rob
[ January 08, 2002: Message edited by: Rob Ross ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic