← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 9 of 10

Java Common Mistakes

Comparing Strings with ==

== compares object references for String, checking whether two variables point to the exact same object in memory, not whether their contents are equal — use .equals() to compare string content correctly.

Example: Comparing Strings with ==

java
public class Main {
	public static void main(String[] args) {
		String a = new String("hi");
		String b = new String("hi");
		System.out.println(a == b); // false: different objects
		System.out.println(a.equals(b)); // true: same content
	}
}

NullPointerException

Calling a method on a variable that's currently null throws NullPointerException, Java's most common runtime error — it usually means a value you assumed was initialized never actually was.

Example: NullPointerException

java
public class Main {
	public static void main(String[] args) {
		String value = null;
		try {
			value.length();
		} catch (NullPointerException e) {
			System.out.println("Caught NullPointerException");
		}
	}
}

Modifying List in For-Each Loop

Calling list.remove() directly while iterating with a for-each loop throws ConcurrentModificationException — use an explicit Iterator and its own remove() method instead when you need to delete elements mid-loop.

Example: Modifying List in For-Each Loop

java
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>(java.util.List.of(1, 2, 3));
		try {
			for (Integer n : list) {
				list.remove(n);
			}
		} catch (java.util.ConcurrentModificationException e) {
			System.out.println("Caught: use Iterator.remove() instead");
		}
	}
}

Array Index Out of Bounds

Accessing an array or list index that's outside its valid range (including using the size itself, which is always one past the last valid index) throws ArrayIndexOutOfBoundsException — a classic off-by-one bug.

Example: Array Index Out of Bounds

java
public class Main {
	public static void main(String[] args) {
		int[] arr = {1, 2, 3};
		try {
			System.out.println(arr[3]); // size itself is one past the last valid index
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Caught: index out of bounds");
		}
	}
}

Integer Division Truncation

Dividing two int values in Java performs integer division and truncates any decimal remainder, so 5 / 2 yields 2, not 2.5 — cast at least one operand to double first if you need a fractional result.

Example: Integer Division Truncation

java
public class Main {
	public static void main(String[] args) {
		System.out.println(5 / 2); // 2: truncated
		System.out.println(5 / (double) 2); // 2.5: cast avoids truncation
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.