aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes do while loop problem 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 "do while loop problem" Watch "do while loop problem" New topic
Author

do while loop problem

Ravi Ahuja
Ranch Hand

Joined: Nov 13, 2006
Posts: 45
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


Impossible is Nothing<br />SCJP 1.4: 96%
swarna dasa
Ranch Hand

Joined: Mar 15, 2007
Posts: 108
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

Joined: Nov 13, 2006
Posts: 45
Thanks you very much that was really a nice way to make me understand Thanks a lot
Ravi Ahuja
Ranch Hand

Joined: Nov 13, 2006
Posts: 45
Thank you very much that explanation was very good Thanks a lot
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: do while loop problem
 
Similar Threads
It should be an Infinite loop.......
JQplus
Question ID :952739442300 JQ+
Doubt on do-while loop
incrementing 'i' ??