• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cant understand programm

 
Rizwan Qadri
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think answer should be 2
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kesava and Ulf
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic