Sitemap

Member-only story

Top 10 Mistakes in Java and How to Avoid Them (With Examples)

5 min readFeb 1, 2025

Java is a powerful, object-oriented programming language that is widely used in enterprise applications, web development, and mobile development. However, even experienced developers make common mistakes that lead to bugs, poor performance, and security vulnerabilities.

For non-members, read this article for free on my blog: Top 10 Mistakes in Java and How to Avoid Them (With Examples)

In this article, we will explore the top 10 most common mistakes in Java and how to avoid them with bad and good code examples.

1️⃣ Using == Instead of .equals() for String Comparison

One of the most common mistakes in Java is comparing Strings using == instead of .equals(). The == operator checks for reference equality, while .equals() checks for value equality.

❌ Bad Code:

String str1 = new String("Java");
String str2 = new String("Java");

if (str1 == str2) { // WRONG: Checks reference, not value
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}

🔴 Output:

Strings are not equal

✅ Good Code:

String str1 = "Java";
String str2 = "Java";

if (str1.equals(str2)) { // CORRECT: Checks actual value
System.out.println("Strings are equal");
}

🟢 Output:

Strings are equal

2️⃣ Forgetting to Override hashCode() When Overriding equals()

In Java, when you override equals(), you must also override hashCode(). Otherwise, collections like HashSet, HashMap, and HashTable won’t function properly.

❌ Bad Code (Only Overriding equals()):

class Employee {
String name;

Employee(String name) {
this.name = name;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Employee)) return false;
Employee emp = (Employee) obj;
return name.equals(emp.name);
}
}

public class Main {
public static void main(String[] args) {
Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Alice");

System.out.println(e1.equals(e2)); // true…

--

--

No responses yet