Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

do while loop problem

 
Ravi Ahuja
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 );
}
}
Answer : A The code will fail to compile, 'while' has an invalid condition expression
Answer : B It will compile but will throw runtime exception
Answer : C It will print 3
Answer : D It will go in an infinite loop
Answer : E It will print 1


The output is it will print 3
I am able to compile the same and am getting the output as 3 but i am really struggling to go through the flow of the program especially the while(b=!b) part
if it returns to true than it should go to an infinte loop else if it comes to false than it should print 2



Source: javabeat
 
swarna dasa
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember it is while(b=!b), so the result will be the value assigned to b.

Lets do a dry run
b = false
i=1
do...
i++ // becomes 2

//value of b is false
while (b=!b) // b is assigned value !b ( !false which is true)
//So condition in while is true

Second iteration
do...
i++ //becomes 3
//b is now true (was assigned in the while statement)
while (b=!b) // b is assigned value !b ( !true which is false)
// Condition is false, get out of the loop

print i which is 3.
[ May 11, 2007: Message edited by: swarna dasa ]
 
Ravi Ahuja
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you very much that was really a nice way to make me understand Thanks a lot
 
Ravi Ahuja
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much that explanation was very good Thanks a lot
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic