Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!

# Evaluate a boolean variable / differences

Thomas Markl
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.

Larry Jones
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.

James Chegwidden
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

Ilja Preuss
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) ...

Dirk Schreckmann
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.

Ruben Steins
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.