This article outlines some of the common mistakes made by Java programmers. Feel free to fill up the list on GitHub with other pitfalls.
Immutable means that once an object is created you cannot change the object itself. Java strings are immutable.
In this example you can update the reference to the object to get the expected result:
s = s.toUpperCase().
BigDecimal and all the wrapper classes for the primitive types are also immutable.
To avoid many mistakes just remember all methods of an immutable object never change the object itself.
equals() vs. ==
- The operator
trueif both object references point to the same object,
equalsmethod should always return
trueif both objects are equivalent (two objects can be equivalent but do not point to the same object).
For example, if we want to compare strings (to see if they contain the same characters), we need to compare the strings using
Saying that, can you guess what the following code prints?
Isn't it a bit weird?
Even though we are testing the strings the wrong way the results are always
true. Why? Because any two string literals consisting of the same characters will actually refer the same object (this object is interned when the program is loaded). The Java Language Specification also stipulates that string-valued constant expressions that concatenates several string literals are interned as a single literal.
These are the reasons why these tests return
Some primitive wrapper classes cache a range of values. For example:
Why? Because integer values between -128 and 127 are cached, but 128 is not.