8 Common Java Errors and Their Solutions
1. NullPointerException
A
NullPointerException occurs when you try to access a method or property through an object reference that contains
null.
Example:
public class NullExample {
public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}
How to Fix It:
Check whether the object is null before accessing it.
String name = null;
if (name != null) {
System.out.println(name.length());
} else {
System.out.println("Name is not available");
}
You can also initialize the variable with a valid value or use
Optional when appropriate.
2. ArrayIndexOutOfBoundsException
This exception occurs when you access an array position outside its valid range. Java arrays start at index 0, so an array containing five elements has indexes from 0 to 4.
Example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[5]); // Throws exception
How to Fix It:
Check the array length before accessing an element.
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
You can also validate individual indexes or use a for-each loop to avoid manual indexing.
3. NumberFormatException
A
NumberFormatException occurs when Java cannot convert a string into a valid numeric value.
Example:
String input = "hello";
int number = Integer.parseInt(input);
How to Fix It:
Use
trim() to remove extra spaces and
try-catch to handle invalid input.
String input = " 123 ";
try {
int number = Integer.parseInt(input.trim());
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number");
}
For values outside the
int range, consider using
Long.parseLong().
4. InputMismatchException
This exception commonly occurs when using
Scanner and entering a value that does not match the expected data type.
Example:
import java.util.Scanner;
public class AgeInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.println(age + 1);
sc.close();
}
}
Entering text instead of an integer causes an
InputMismatchException.
How to Fix It:
Use
hasNextInt() to validate input before reading it.
import java.util.Scanner;
public class AgeInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
while (!sc.hasNextInt()) {
System.out.print("Enter a valid integer: ");
sc.next();
}
int age = sc.nextInt();
System.out.println("Next year: " + (age + 1));
sc.close();
}
}
5. ClassCastException
A
ClassCastException occurs when you try to convert an object into an incompatible type.
Example:
public class CastExample {
public static void main(String[] args) {
Object obj = "Hello";
Integer number = (Integer) obj;
}
}
Here, the object contains a
String, so converting it directly into an
Integer causes an exception.
How to Fix It:
Use
instanceof before casting.
Object obj = "Hello";
if (obj instanceof Integer) {
Integer number = (Integer) obj;
System.out.println(number);
} else {
System.out.println("Object is not an Integer");
}
Using generics, such as
List, also helps prevent incompatible types in collections.
6. ConcurrentModificationException
This exception occurs when you directly modify a collection, such as an
ArrayList, while iterating over it.
Example:
import java.util.*;
public class ConcurrentExample {
public static void main(String[] args) {
List languages = new ArrayList<>(
Arrays.asList("Java", "Python", "C++")
);
for (String language : languages) {
if (language.startsWith("J")) {
languages.remove(language);
}
}
}
}
How to Fix It:
Use the iterator’s
remove() method or
removeIf().
List numbers = new ArrayList<>(
Arrays.asList(10, 15, 20, 35)
);
numbers.removeIf(number -> number % 2 == 0);
System.out.println(numbers); // [15, 35]
For maps, you can also use
removeIf() on the entry set.
7. StackOverflowError
A
StackOverflowError occurs when too many method calls fill the available call stack. It commonly happens when a recursive method has no proper stopping condition.
Example:
public class StackExample {
static int factorial(int n) {
return n * factorial(n - 1);
}
public static void main(String[] args) {
factorial(5);
}
}
How to Fix It:
Add a base case to stop recursion.
static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Always check that recursive calls move towards the base case. For very large inputs, consider replacing recursion with a loop.
8. ArithmeticException
An
ArithmeticException commonly occurs when you divide an integer by zero.
Example:
int a = 10;
int b = 0;
int result = a / b; // Throws ArithmeticException
How to Fix It:
Check the divisor before performing division.
int a = 10;
int b = 0;
if (b != 0) {
System.out.println(a / b);
} else {
System.out.println("Cannot divide by zero");
}
Note that dividing a
double by zero produces
Infinity or
NaN rather than an
ArithmeticException.
Creating and Throwing Custom Exceptions in Java
Java allows you to create custom exceptions when built-in exceptions do not describe a particular problem.
Use
Exception for checked exceptions and
RuntimeException for unchecked exceptions.
Example:
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class Wallet {
private double balance = 50;
public void withdraw(double amount)
throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Insufficient account balance"
);
}
balance -= amount;
}
}
Here,
throw raises the exception, while
throws declares that the method may pass it to the caller.
Difference Between throw and throws
| throw |
throws |
| Used inside a method |
Used in a method declaration |
| Raises an exception |
Declares possible exceptions |
| Followed by an exception object |
Followed by exception class names |
Example: throw new IOException() |
Example: throws IOException |
How to Debug Java Errors Step by Step
Follow these steps to identify and fix Java errors:
- Read the error message: Identify the exception name and understand what went wrong.
- Check the stack trace: Find the file and line number where the error occurred.
- Inspect variables: Check for null values, invalid indexes, and unexpected input.
- Use print statements: Display variable values before the problematic line.
- Use an IDE debugger: Set breakpoints and inspect program execution in IntelliJ IDEA, Eclipse, or VS Code.
- Search for solutions: Consult Java documentation and reliable programming communities.
- Create a smaller example: Isolate the problematic code to identify the cause more easily.
Use Logging Instead of Print Statements
For larger programs,
Java’s built-in logger helps record debugging information without relying on multiple print statements.
import java.util.logging.Logger;
public class GradeCalculator {
private static final Logger LOG =
Logger.getLogger(GradeCalculator.class.getName());
static char letterGrade(int score) {
LOG.info("Score received: " + score);
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
return 'F';
}
}
Logging makes it easier to track program activity and control which messages appear.
Need Help With Your Java Programming Assignments?
Struggling with Java errors or programming assignments? Campus Academic Help supports students in understanding coding concepts, identifying mistakes, and improving problem-solving skills through clear, step-by-step academic guidance.