Errors/Java

Common Java Errors

Java errors including NullPointerException, ClassCastException, OutOfMemoryError, ConcurrentModificationException, and more.

60 errors documented with step-by-step fixes

NullPointerException

java.lang.NullPointerException

You are calling a method or accessing a field on a null reference. Check that the object is initialized before using it.

NullPointerException During Unboxing

java.lang.NullPointerException: Cannot invoke method because the return value is null

You are unboxing a null wrapper type (like Integer or Boolean) to a primitive. Use the wrapper type or add a null check.

ArrayIndexOutOfBoundsException

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

You are accessing an array with an index that is negative or greater than or equal to its length. Remember arrays are zero-indexed.

StringIndexOutOfBoundsException

java.lang.StringIndexOutOfBoundsException: String index out of range: 10

You are accessing a character in a string at an index that exceeds its length. Check the string length before calling charAt() or substring().

IndexOutOfBoundsException on List

java.lang.IndexOutOfBoundsException: Index: 3, Size: 2

You are accessing a List element at an index that is out of range. Check the list size before calling get().

ClassCastException

java.lang.ClassCastException: class java.lang.String cannot be cast to java.lang.Integer

You are casting an object to an incompatible type. Use instanceof to check the type before casting.

ClassNotFoundException

java.lang.ClassNotFoundException: com.example.MyClass

The JVM cannot find the specified class at runtime. The class is missing from the classpath or the name is misspelled.

NoClassDefFoundError

java.lang.NoClassDefFoundError: com/example/MyClass

A class that was available at compile time is missing at runtime. Check that all required JARs are on the runtime classpath.

StackOverflowError

java.lang.StackOverflowError

Your code has infinite or excessively deep recursion. Add a base case to your recursive method or convert to iteration.

OutOfMemoryError: Java Heap Space

java.lang.OutOfMemoryError: Java heap space

The JVM has run out of heap memory. You are either allocating too many objects, have a memory leak, or need to increase the heap size.

OutOfMemoryError: GC Overhead Limit Exceeded

java.lang.OutOfMemoryError: GC overhead limit exceeded

The garbage collector is spending more than 98% of time collecting with less than 2% of heap recovered. You have a memory leak or insufficient heap.

OutOfMemoryError: Metaspace

java.lang.OutOfMemoryError: Metaspace

The JVM ran out of metaspace, which stores class metadata. You are loading too many classes or have a classloader leak.

OutOfMemoryError: Unable to Create New Native Thread

java.lang.OutOfMemoryError: unable to create new native thread

The JVM cannot create more OS threads. You are creating too many threads or the OS thread limit has been reached.

ConcurrentModificationException

java.util.ConcurrentModificationException

You are modifying a collection while iterating over it. Use an Iterator's remove method or collect changes and apply them after iteration.

IllegalArgumentException

java.lang.IllegalArgumentException: Invalid argument value

You passed an argument that is outside the valid range or violates a precondition. Check the method documentation for valid argument constraints.

IllegalStateException

java.lang.IllegalStateException: Iterator already started

You are calling a method at a time when the object is not in the correct state for that operation. Check the object lifecycle.

UnsupportedOperationException

java.lang.UnsupportedOperationException

You are calling a mutating method on an unmodifiable collection. Use a mutable collection like ArrayList instead.

NumberFormatException

java.lang.NumberFormatException: For input string: "abc"

You are parsing a string that is not a valid number. Validate the input string before parsing or handle the exception.

FileNotFoundException

java.io.FileNotFoundException: /path/to/file.txt (No such file or directory)

The specified file does not exist or the path is incorrect. Verify the file path and check that the file exists before opening it.

IOException

java.io.IOException: Stream closed

An I/O operation failed, often because a stream was already closed or a connection was lost. Use try-with-resources to manage streams properly.

SocketException: Connection Reset

java.net.SocketException: Connection reset

The remote server unexpectedly closed the connection. Implement retry logic and handle the disconnection gracefully.

ConnectException: Connection Refused

java.net.ConnectException: Connection refused

The target server is not listening on the specified port. Verify the host, port, and that the server is running.

UnknownHostException

java.net.UnknownHostException: invalid.hostname.example

DNS cannot resolve the hostname. Check for typos in the hostname and verify network/DNS configuration.

NoSuchMethodError

java.lang.NoSuchMethodError: com.example.MyClass.doSomething()V

A method that existed at compile time is missing at runtime. You have a version mismatch between compile-time and runtime dependencies.

AbstractMethodError

java.lang.AbstractMethodError: Receiver class does not define or inherit an implementation

A class is missing the implementation of an abstract method. This is usually a dependency version mismatch where the interface changed.

ArithmeticException: Division by Zero

java.lang.ArithmeticException: / by zero

You are dividing an integer by zero. Check the divisor is not zero before performing the division.

NegativeArraySizeException

java.lang.NegativeArraySizeException: -5

You are creating an array with a negative size. Validate that the size is non-negative before array creation.

Classpath Conflict: Duplicate Classes

java.lang.LinkageError: loader constraint violation

The same class is loaded by different classloaders or exists in multiple JARs on the classpath. Remove the duplicate dependency.

NoSuchElementException from Optional.get()

java.util.NoSuchElementException: No value present

You called get() on an empty Optional. Use orElse(), orElseGet(), or ifPresent() instead of get().

NoSuchElementException from Iterator

java.util.NoSuchElementException

You called next() on an iterator that has no more elements. Always check hasNext() before calling next().

IllegalMonitorStateException

java.lang.IllegalMonitorStateException

You called wait(), notify(), or notifyAll() on an object without holding its monitor. These methods must be called inside a synchronized block on the same object.

InterruptedException

java.lang.InterruptedException

The thread was interrupted while waiting, sleeping, or blocked. Handle the interruption by either re-interrupting the thread or stopping the task.

TimeoutException

java.util.concurrent.TimeoutException

A blocking operation did not complete within the specified timeout. Increase the timeout or investigate why the operation is slow.

ExecutionException

java.util.concurrent.ExecutionException: java.lang.RuntimeException: Task failed

A task submitted to an executor threw an exception. The real cause is wrapped inside the ExecutionException. Call getCause() to find it.

ClassFormatError: Unsupported Major.Minor Version

java.lang.UnsupportedClassVersionError: com/example/MyClass has been compiled by a more recent version of the Java Runtime

The class was compiled with a newer Java version than you are running. Upgrade your JRE or recompile with a compatible target version.

AccessDeniedException (File Permission)

java.nio.file.AccessDeniedException: /path/to/file.txt

The Java process does not have permission to access the file. Check file permissions and ensure the process user has read/write access.

DateTimeParseException

java.time.format.DateTimeParseException: Text '2024-13-01' could not be parsed

The date/time string does not match the expected format or contains invalid values. Check the format pattern and input values.

Incompatible Types with Generics

error: incompatible types: List<Object> cannot be converted to List<String>

Java generics are invariant. List<Object> is not a supertype of List<String>. Use wildcards like List<? extends Object> for flexibility.

Unchecked Cast Warning

warning: [unchecked] unchecked cast: Object to List<String>

You are casting a raw or Object type to a parameterized type. This is unsafe because generic type information is erased at runtime.

Thread Deadlock

Found one Java-level deadlock: Thread-1 waiting on lock held by Thread-2, Thread-2 waiting on lock held by Thread-1

Two or more threads are each waiting for a lock held by the other. Always acquire locks in a consistent order.

OutOfMemoryError: Direct Buffer Memory

java.lang.OutOfMemoryError: Direct buffer memory

You have exhausted the direct (off-heap) memory allocated for NIO buffers. Increase -XX:MaxDirectMemorySize or fix the buffer leak.

Compilation Error: Invalid Method Reference

error: incompatible types: invalid method reference. Cannot make a static reference to the non-static method

You are using a static method reference syntax for an instance method or vice versa. Match the method reference form to the method type.

Lambda Expression Target Type Error

error: incompatible types: lambda expression target type must be a functional interface

A lambda can only be assigned to a functional interface (interface with exactly one abstract method). The target type must be a @FunctionalInterface.

InvalidClassException: SerialVersionUID Mismatch

java.io.InvalidClassException: com.example.User; local class incompatible: stream classdesc serialVersionUID = 123, local class serialVersionUID = 456

The serialized data was written with a different version of the class. Define an explicit serialVersionUID to maintain compatibility across class changes.

ExceptionInInitializerError

java.lang.ExceptionInInitializerError

A static initializer or static field initialization threw an exception. Check the caused-by chain for the actual error in the static block.

Compile Error: Unreachable Statement

error: unreachable statement

You have code after a return, throw, break, or continue statement that can never execute. Remove the dead code or restructure the control flow.

Compile Error: Missing Return Statement

error: missing return statement

Not all code paths in your method return a value. Add return statements to every branch or add a default return at the end.

Compile Error: Variable Might Not Have Been Initialized

error: variable result might not have been initialized

A local variable is used before it is guaranteed to be assigned. Initialize it at declaration or ensure all code paths assign it.

Resource Leak: Stream Not Closed

warning: [resource] resource of type InputStream is never closed

You opened an I/O resource without closing it. Use try-with-resources to ensure automatic cleanup.

PatternSyntaxException

java.util.regex.PatternSyntaxException: Unclosed group near index 5

Your regular expression has invalid syntax. Check for unescaped special characters, unclosed groups, or invalid quantifiers.

MissingFormatArgumentException

java.util.MissingFormatArgumentException: Format specifier '%s'

Your format string has more placeholders than arguments. Add the missing arguments or remove extra format specifiers.

Requested Array Size Exceeds VM Limit

java.lang.OutOfMemoryError: Requested array size exceeds VM limit

You are trying to allocate an array larger than the JVM allows. The maximum array size is approximately Integer.MAX_VALUE - 5.

Compile Error: Cannot Find Symbol

error: cannot find symbol. symbol: variable myVariable

The compiler cannot find the variable, method, or class you referenced. Check for typos, missing imports, or scope issues.

Compile Error: Non-static Method Referenced from Static Context

error: non-static method process() cannot be referenced from a static context

You are calling an instance method from a static method (like main) without creating an object first. Create an instance or make the method static.

Compile Error: Unhandled Exception

error: unreported exception IOException; must be caught or declared to be thrown

You are calling a method that throws a checked exception without handling it. Add a try-catch block or declare the exception in your method signature.

Compile Error: Not AutoCloseable in Try-with-Resources

error: incompatible types: MyClass cannot be converted to AutoCloseable

The class used in try-with-resources does not implement AutoCloseable. Implement the interface or close the resource manually.

NullPointerException with ConcurrentHashMap

java.lang.NullPointerException: Cannot invoke method on null key/value in ConcurrentHashMap

ConcurrentHashMap does not allow null keys or values, unlike HashMap. Check for null before inserting or use HashMap if null is needed.

StackOverflowError in toString()

java.lang.StackOverflowError at com.example.User.toString(User.java:25)

Your toString() method creates infinite recursion, usually by referencing another object whose toString() references back. Break the circular reference.

Compile Error: Incompatible Return Type

error: incompatible types: String cannot be converted to int

The method returns a type that does not match its declared return type. Fix the return statement or change the method signature.

MalformedInputException: Character Encoding Error

java.nio.charset.MalformedInputException: Input length = 1

The byte sequence is invalid for the specified character encoding. Use the correct charset or handle malformed input with CodingErrorAction.REPLACE.

Bugsly catches Java errors automatically

AI-powered error tracking that explains what went wrong and suggests fixes. Set up in 2 minutes.

Get Started Free