Java Common Mistakes
In this page:
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 ==
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
String value = null;
try {
value.length();
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: