This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Meteor in Action and have Stephan Hochhaus & Manuel Schoebel on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Cant understand programm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Meteor in Action this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Cant understand programm" Watch "Cant understand programm" New topic
Author

Cant understand programm

Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Hi, All
Please help me to understand this program.

class BoleanTest
{

public static void main(String args[])
{
boolean b = false;

int i = 1;
do{
i++ ;
} while (b =!b);
System.out.println( i );

}
}

O/P is 3
Why???
Ulf Dittmer
Rancher

Joined: Mar 22, 2005
Posts: 42955
    
  73
I think you'll learn more if you first describe to us what you think the output should be, and why. Then we can help you understand what the program does.
Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
I think answer should be 2
Kishore Kumar
Ranch Hand

Joined: Oct 15, 2007
Posts: 71
class BoleanTest
{

public static void main(String args[])
{
boolean b = false;

int i = 1;
do{
i++ ;
} while (b =!b);
System.out.println( i );

}
}
You know that do while loop executes atleast once:
so for the first time i is incremented to 2.
Now the while condition.
b =!b.... This is executed as b = (!false) = true.
So again loop is executed and i is incremented to 3.
Next the condition becomes as b = (!true) = false.
Control comes out of the loop.
Finally i is printed which is 3.
Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Thanks Kesava and Ulf
 
Consider Paul's rocket mass heater.
 
subject: Cant understand programm