programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Evaluate a boolean variable / differences

Ranch Hand
Posts: 192
1.
boolean x = true;
while (true);
....
2.
boolean x = true;
while (x == true);
....
3.
boolean x = true;
while (x=true);
....

What is the difference between this 3 expressions?
Thomas.

Greenhorn
Posts: 24
while(true)--This one would be an infinite loop. There is no expression that is going to evaluate. The only way to get out of this loop is a break statement.
while (x == true)--This is a boolean expression that will evaluate to either true or false based on the value of x. If x is true, the expression will evaluate to true. If x is false, the expression will evaluate to false.

while(x=true)--I am not completely sure about this one, but I think I got it. This is an assignment statement, not a comparison. So here you are assigning a value of true to x, and then x evaluates to true.

Author
Ranch Hand
Posts: 201

while(x=true)--I am not completely sure about this one, but I think I got it. This is an assignment statement, not a comparison. So here you are assigning a value of true to x, and then x evaluates to true.

Yep, you are assigning true to x and the evaluating the loop

author
Sheriff
Posts: 14112

Originally posted by Larry Jones:

while (x == true)--This is a boolean expression that will evaluate to either true or false based on the value of x. If x is true, the expression will evaluate to true. If x is false, the expression will evaluate to false.

So it has the same effect as
while (x) ...

Sheriff
Posts: 7023
...and you have discovered that all expressions (including expressions that involve an assignment operator) create a return value. So, an assignment expression also represents some value.
[ November 12, 2002: Message edited by: Dirk Schreckmann ]

James Chegwidden
Author
Ranch Hand
Posts: 201
Yep, that is why a C or C++ background can help.

Greenhorn
Posts: 15
This only works for booleans in Java afaik (as opposed to C/C++). In C and C++ the result of an assignment ( x=y ) will always be true if y is nonzero. In Java, the result of this expression is not a boolean (unless you're assigning a boolean value) and it will give a compile-time error.

 Don't get me started about those stupid light bulbs.