Among the common pitfalls, well known but still biting occasionally programmers, there is the classical if (a = b)
which is found in all C-like languages.
In Java, it can work only if a and b are boolean, of course. But I see too often newbies testing like if (a == true)
(while if (a)
is shorter, more readable and safer...) and occasionally writing by mistake if (a = true)
, wondering why the test doesn't work.
For those not getting it: the last statement first assign true
to a
, then do the test, which always succeed!
-
One that bites lot of newbies, and even some distracted more experienced programmers (found it in our code), the if (str == "foo")
. Note that I always wondered why Sun overrode the + sign for strings but not the == one, at least for simple cases (case sensitive).
For newbies: ==
compares references, not the content of the strings. You can have two strings of same content, stored in different objects (different references), so ==
will be false.
Simple example:
final String F = "Foo";
String a = F;
String b = F;
assert a == b; // Works! They refer to the same object
String c = "F" + F.substring(1); // Still "Foo"
assert c.equals(a); // Works
assert c == a; // Fails
-
And I also saw if (a == b & c == d)
or something like that. It works (curiously) but we lost the logical operator shortcut (don't try to write: if (r != null & r.isSomething())
!).
For newbies: when evaluating a && b
, Java doesn't evaluate b if a is false. In a & b
, Java evaluates both parts then do the operation; but the second part can fail.
[EDIT] Good suggestion from J Coombs, I updated my answer.