5 Common Mistakes in Java

Maneesha Jayasundara
3 min readJun 10, 2021

Sometimes common is not very common. We knew or read or learned some things a while back but with time, we tend to forget the basic concepts. I have seen many developers make these mistakes.

So, let’s refresh our simple and common java concepts.

1. “==” vs “equals()”

There is a humungous difference between “==” and “equals()”. These both can’t replace one another in any scenario. “==” is used to check the reference of two objects while “equals()” is used to check the values inside those 2 objects in the java. Have a look at the below examples:

2. Mistake with equals() method

Whenever comparing any value with literal or constant, make sure to put literal before equals() method. If you put the getter() method first, then there is a possible chance for NullPointerException.

Hence, the correct way is to put constant value first as shown below. Or null check would also work but I guess it would be just an additional if-statement.

3. Most common exception: NullPointerException

Though precaution is good to take, over-precaution is not. To avoid NullPointerException, sometimes developer tends to null check each and everything even inside the “for-each” loop. But there is no need to check for a null inside loop. The “for-each” loop iterates only when there is an element present in the list. Look at the below examples for affirmation:

See, there is no NullPointerException! Hence, the below null check is not required.

4. Take a break

Many times, missing the break statement in the switch case remain undiscovered until run in production.

If you have forgotten a break in case 0 in the code example, the program will write “Zero” followed by “One”, since the control flow inside here will go through the entire switch statement until it reaches a break. Hence, check once again while writing the switch case.

5. ConcurrentModificationException

ConcurrentModificationException occurs when a collection is modified while iterating it. Consider an instance, we have a list of people and want to

remove one person from it. If we run this code, a Concurrent Modification Exception will be raised. To solve this, there are various ways available. Firstly, collect object and remove them in another loop. Or you could use Iterator.remove() method.

This approach is more concise, and it doesn’t need to create an additional collection.

Hope you like it. 😊🙌

--

--