The Most Common Java Pitfalls

OlogN
1,732 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Pitfalls

This article outlines some of the common mistakes made by Java programmers. Feel free to fill up the list on GitHub with other pitfalls.

Immutability

Immutable means that once an object is created you cannot change the object itself. Java strings are immutable.

What does it print?
1
9
10
11
12
13
14
15
// {...}
String s = "abc";
s.toUpperCase();
System.out.println(s);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In this example you can update the reference to the object to get the expected result: s = s.toUpperCase().
BigInteger, BigDecimal and all the wrapper classes for the primitive types are also immutable.

What does it print?
1
11
12
13
14
15
16
17
// {...}
BigInteger b = new BigInteger("1000");
b.add(new BigInteger("2"));
System.out.println(b);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

To avoid many mistakes just remember all methods of an immutable object never change the object itself.

equals() vs. ==

  • The operator == returns true if both object references point to the same object, false otherwise.
  • The equals method should always return true if 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 equals.

Saying that, can you guess what the following code prints?

What does it print?
1
9
10
11
12
13
14
15
16
17
// {...}
String s1 = "text";
String s2 = "text";
String s3 = "t" + "ext";
System.out.println(s1 == s2); // true or false?
System.out.println(s2 == s3); // true or false?
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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 true.

Some primitive wrapper classes cache a range of values. For example:

What does it print?
1
9
10
11
12
13
14
15
16
17
18
// {...}
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b); // true or false?
System.out.println(c == d); // true or false?
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Why? Because integer values between -128 and 127 are cached, but 128 is not.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content