Java/JVM Error Fixes -- How to Fix Common Java Errors
Java errors like NullPointerException and OutOfMemoryError crash your JVM application instantly -- this guide shows you how to diagnose and fix the most common Java and JVM errors with stack trace analysis and proven solutions.
What You'll Learn
Why It Matters
Java and the JVM power enterprise applications worldwide. Understanding these common errors helps you debug production issues faster and write more robust Java code.
Real-World Use
When your Spring Boot application throws a NullPointerException in production or a batch job hits an OutOfMemoryError, knowing the exact fix prevents downtime and data loss.
Common Java Errors Table
| Error Message | Cause | Fix |
|---|---|---|
| java.lang.NullPointerException | Calling a method on a null object reference | Add null checks with if (obj == null) or use Optional |
| java.lang.ClassNotFoundException | Required class not on classpath | Add the JAR dependency to classpath or build file |
| java.lang.OutOfMemoryError: Java heap space | JVM ran out of heap memory | Increase -Xmx JVM parameter or fix memory leak |
| java.util.ConcurrentModificationException | Modifying a collection while iterating | Use <a href="/design-patterns/iterator/">Iterator</a>.remove() or ConcurrentHashMap |
| java.lang.ArrayIndexOutOfBoundsException | Accessing array index beyond length | Check index with if (i < array.length) before access |
| java.lang.NumberFormatException | Parsing a non-numeric string | Wrap in try-catch or validate with regex first |
| java.lang.StackOverflowError | Infinite recursion or deep call stack | Add base case or increase stack size with -Xss |
Step-by-Step Fixes
Fix 1: NullPointerException
// Bad.java
public class Bad {
public static void main(String[] args) {
String name = null;
System.out.println(name.length()); // NullPointerException
}
}
// Fixed.java
public class Fixed {
public static void main(String[] args) {
String name = null;
if (name != null) {
System.out.println(name.length());
} else {
System.out.println("Name is null");
}
// Or using Optional
java.util.Optional.ofNullable(name)
.ifPresentOrElse(
n -> System.out.println(n.length()),
() -> System.out.println("Name is null")
);
}
}
Expected output:
Name is null
Fix 2: ClassNotFoundException
# bad
javac App.java
java App
# Exception in thread "main" java.lang.ClassNotFoundException: com.google.gson.Gson
# fixed -- add the JAR to the classpath
# Download gson.jar and compile with classpath
javac -cp gson-2.10.1.jar App.java
java -cp .:gson-2.10.1.jar App
# Or better, use Maven/Gradle
# Add to pom.xml:
# <dependency>
# <groupId>com.google.code.gson</groupId>
# <artifactId>gson</artifactId>
# <version>2.10.1</version>
# </dependency>
Expected output:
{"name": "Alice", "age": 30}
Fix 3: OutOfMemoryError -- Java Heap Space
# bad
java -jar myapp.jar
# Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
# fixed -- increase heap memory
java -Xmx4g -Xms1g -jar myapp.jar
# Check current heap usage
jcmd myapp.jar VM.flags | grep HeapSize
# Profile heap dump to find the leak
# jmap -dump:live,format=b,file=heap.hprof <pid>
Expected output:
# Application starts successfully with 4GB heap
# (no OutOfMemoryError)
Fix 4: ConcurrentModificationException
// Bad.java
import java.util.*;
public class Bad {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String item : list) {
if (item.equals("B")) {
list.remove(item); // ConcurrentModificationException
}
}
}
}
// Fixed.java
import java.util.*;
public class Fixed {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("B")) {
it.remove(); // safe removal with iterator
}
}
System.out.println(list); // [A, C]
}
}
Expected output:
[A, C]
Fix 5: ArrayIndexOutOfBoundsException
// Bad.java
public class Bad {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i <= numbers.length; i++) { // <= causes OOB
System.out.println(numbers[i]);
}
}
}
// Fixed.java
public class Fixed {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) { // < instead of <=
System.out.println(numbers[i]);
}
}
}
Expected output:
10
20
30
Fix 6: NumberFormatException
// Bad.java
public class Bad {
public static void main(String[] args) {
String input = "abc";
int number = Integer.parseInt(input); // NumberFormatException
System.out.println(number);
}
}
// Fixed.java
public class Fixed {
public static void main(String[] args) {
String input = "abc";
try {
int number = Integer.parseInt(input);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + input);
}
}
}
Expected output:
Invalid number: abc
Java Error Diagnosis Flowchart
flowchart TD
A[Java Error Detected] --> B{Error Type?}
B -->|NullPointerException| C[Check object initialization]
C --> D[Add null checks or use Optional]
B -->|ClassNotFoundException| E[Check classpath and dependencies]
E --> F[Add JAR to classpath or build file]
B -->|OutOfMemoryError| G[Check heap usage]
G --> H[Increase -Xmx or fix memory leak]
B -->|ConcurrentModification| I[Use Iterator.remove]
I --> J[Or use CopyOnWriteArrayList]
B -->|ArrayIndexOutOfBounds| K[Check loop bounds]
K --> L[Use < instead of <=]
B -->|NumberFormatException| M[Validate input before parse]
M --> N[Use try-catch or regex]
D --> O[Error Resolved]
F --> O
H --> O
J --> O
L --> O
N --> O
Prevention Tips
- Use
Optional<T>return types instead of returning null from methods - Annotate nullable fields with
@Nullableand use IDE null analysis - Always validate string inputs with regex before parsing to integers or doubles
- Use
<a href="/design-patterns/iterator/">Iterator</a>.remove()orList.removeIf()when modifying collections during iteration - Set JVM memory limits with
-Xmxbased on application profiling data - Use try-catch blocks around all external input parsing operations
- Enable
-XX:+HeapDumpOnOutOfMemoryErrorto capture heap dumps for analysis
Practice Questions
What causes a NullPointerException and how do you prevent it? Answer: Calling a method or field on a null object reference. Prevent it with null checks,
Optional, or@Nullableannotations.How do you fix an OutOfMemoryError in a Java application? Answer: Increase heap with
-Xmxflag, or find and fix the memory leak using a heap dump profiler like Eclipse MAT.What is ConcurrentModificationException and how do you avoid it? Answer: It occurs when you modify a collection while iterating over it. Use
<a href="/design-patterns/iterator/">Iterator</a>.remove()orCopyOnWriteArrayListfor concurrent access.How do you handle NumberFormatException when parsing user input? Answer: Wrap
Integer.parseInt()orDouble.parseDouble()in a try-catch block, or validate the input format with a regex first.Challenge: Write a Java utility method that safely retrieves a nested value from a chain of objects that may be null at any level, without throwing NullPointerException, and returns a default value if any level is null. Answer:
import java.util.Optional; import java.util.function.Supplier; public class SafeNavigator { public static <T> T safeGet(Supplier<T> getter, T defaultValue) { try { return Optional.ofNullable(getter.get()).orElse(defaultValue); } catch (NullPointerException e) { return defaultValue; } } public static void main(String[] args) { // Usage: safeGet(() -> user.getProfile().getName(), "Unknown") String name = safeGet(() -> { // Simulate deep nested access User user = new User(); return user.getProfile().getName(); }, "Unknown"); System.out.println(name); // Unknown (no NPE) } } class User { Profile getProfile() { return null; } } class Profile { String getName() { return "Alice"; } }
Quick Reference
| Error | Cause | Quick Fix |
|---|---|---|
| NullPointerException | Null object dereference | Add null check or use Optional |
| ClassNotFoundException | Missing JAR dependency | Add JAR to classpath or Maven/Gradle |
| OutOfMemoryError | Heap exhausted | Increase -Xmx or fix memory leak |
| ConcurrentModification | Modifying during iteration | Use <a href="/design-patterns/iterator/">Iterator</a>.remove() |
| ArrayIndexOutOfBounds | Wrong loop bound | Use < array.length not <= |
| NumberFormatException | Invalid string parse | Wrap in try-catch |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro