Java - Common Gotchas [closed]
In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.
I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.
See also:
- Perl - Common gotchas
- .NET - Common gotchas
Solution 1:
Comparing equality of objects using ==
instead of .equals()
-- which behaves completely differently for primitives.
This gotcha ensures newcomers are befuddled when "foo" == "foo"
but new String("foo") != new String("foo")
.
Solution 2:
"a,b,c,d,,,".split(",").length
returns 4, not 7 as you might (and I certainly did) expect. split
ignores all trailing empty Strings returned. That means:
",,,a,b,c,d".split(",").length
returns 7! To get what I would think of as the "least astonishing" behaviour, you need to do something quite astonishing:
"a,b,c,d,,,".split(",",-1).length
to get 7.