• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

flow control

 
Yuki Cho
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code prints out 3. I thought it will go in an infinite loop since it is while (true), but it is not. Please explain... thanx!!!
-----------
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 );
}
}
 
Lam Thai
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Yuki Cho:
The following code prints out 3. I thought it will go in an infinite loop since it is while (true), but it is not. Please explain... thanx!!!
-----------
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 );
}
}

Hi Yuki,
Pay attention to the while statement:
while (b = !b)
The first time, when b = false, read that statement as
while (b = !false) or while (b = true) // b is now assigned a value 'true'
Next time around, b is true, read that statement to be
while (b = !true) or while (b = false) // b is now assigned a value 'false' -> hence your loop is broken.
Take care,
- Lam -
 
mousami bhattacharya
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
If you see carefully the while condition has (b = !b) an assignment not conditional operator(==),so the first time it executes fine (b is given true) and i gets value 2 ,next time ,after i is incremented to value 3 ,the b gets value false( b= !b) and hence exits do-while loop
Hope this helps
M
Originally posted by Yuki Cho:
The following code prints out 3. I thought it will go in an infinite loop since it is while (true), but it is not. Please explain... thanx!!!
-----------
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 );
}
}

 
Yuki Cho
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
thanks for pointing this out. i think i can easily missed this kind of concept. thanx!!!
-yuki
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic