I know that we cant use assignment operator in if statements in java as we use in any other few languages.
that is
int a;
if(a = 1) { }
will give a compilation error.
but the following code works fine, how?
boolean b;
if(b = true) { }
EDIT : Is this the exception to rule that assignment cant be used in if statement.
Because the “result” of an assignment is the value assigned… so it’s still a
booleanexpression in the second case.ifexpressions require the condition to be abooleanexpression, which is satisfied by the second but not the first. Effectively, your two snippets are:and
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 ofif (b == true)andif (!b)instead ofif (b == false). You still get into problems withif (b == c) whenbandcarebooleanvariables, 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
ifstatements – andwhileloops etc, so long as the overall condition expression isboolean. For example, you might have: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.”