aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes flow control Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "flow control " Watch "flow control " New topic
Author

flow control

Yuki Cho
Ranch Hand

Joined: Apr 18, 2001
Posts: 31
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

Joined: Apr 02, 2001
Posts: 117
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

Joined: May 13, 2001
Posts: 40
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

Joined: Apr 18, 2001
Posts: 31
hi guys,
thanks for pointing this out. i think i can easily missed this kind of concept. thanx!!!
-yuki
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: flow control