Because the "result" of an assignment is the value assigned... so it's still a boolean
expression in the second case. if
expressions require the condition to be a boolean
expression, which is satisfied by the second but not the first. Effectively, your two snippets are:
int a;
a = 1;
if (a) { }
and
boolean b;
b = true;
if (b) { }
Is it clear from that expansion that the second version will compile but not the first?
This is one reason not to do comparisons with true and false directly. So I would always just write if (b)
instead of if (b == true)
and if (!b)
instead of if (b == false)
. You still get into problems with if (b == c
) when b
and c
are boolean
variables, admittedly - a typo there can cause an issue. I can't say it's ever happened to me though.
EDIT: Responding to your edit - assignments of all kinds can be used in if
statements - and while
loops etc, so long as the overall condition expression is boolean
. For example, you might have:
String line;
while ((line = reader.readLine()) != null)
{
// Do something with a line
}
While I usually avoid side-effects in conditions, this particular idiom is often useful for the example shown above, or using InputStream.read
. Basically it's "while the value I read is useful, use it."
if (a == true)
, right? – Daiquiriif ( $a == $b )
. Horrible to read, nobody says '5 is a'. It's easier to just be more careful when writingif
conditions, IMO. – Geulincxif(foo = x)
or something like that. – Strother