CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Top 10 Common Java Errors

Java Tutorial Menu

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

Top 10 Common Java Errors

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Published: February 28, 2022 · 6 min read · 0 Comments
Share: X in 🔗

Java errors can disturb our coding flow especially when we’re unsure why they’re happening. In this guide, we’ll break down the Top 10 common Java errors, explain their causes, and provide actionable fixes. Whether you’re a beginner or a seasoned developer, these solutions will save you hours of debugging!

Table of Contents

  • 1. NullPointerException
  • 2. ClassNotFoundException
  • 3. NoClassDefFoundError
  • 4. “Could not find or load main class”
  • 5. ArrayIndexOutOfBoundsException
  • 6. UnsupportedClassVersionError
  • 7. NoSuchMethodError
  • 8. OutOfMemoryError
  • 9. “Exception in thread main” (Generic Runtime Errors)
  • 10. “javac is not recognized” (Compilation Error)
  • Tips for Handling Common Errors in Java
    • Use specific exception classes
    • Log exceptions
    • Don’t swallow exceptions
    • Use finally blocks
    • Use try-with-resources
  • Troubleshooting Tips for Java Errors
  • Additional Tips
  • Final Thoughts

1. NullPointerException

Error Message:
Exception in thread "main" java.lang.NullPointerException

Cause:
Trying to access a method or property of an object that is null.

Example:

String text = null;  
System.out.println(text.length()); // Throws NullPointerException  

Fix:

  • Initialize objects before using them.
  • Add null checks:
if (text != null) {  
    System.out.println(text.length());  
}  

There is a detail post on how to avoid NullPointerException. You can check that out.

2. ClassNotFoundException

Error Message:
java.lang.ClassNotFoundException

Cause:
The JVM can’t find the specified class at runtime. Common in projects with missing dependencies or incorrect classpaths.

Fix:

  • Ensure the class is in the correct package.
  • Add missing JAR files to your project’s build path (e.g., in Eclipse: Right-click project > Build Path > Configure Build Path).
  • For Maven/Gradle, update dependencies in pom.xml or build.gradle.

3. NoClassDefFoundError

Error Message:
java.lang.NoClassDefFoundError

Cause:
A class was present during compilation but missing at runtime.

Fix:

  • Check if the JAR file containing the class is included in the runtime classpath.
  • Rebuild the project to ensure all dependencies are bundled.

4. “Could not find or load main class”

Error Message:
Error: Could not find or load main class MainClass

Cause:

  • Incorrect class name specified in the java command.
  • Missing Main-Class attribute in the JAR manifest.

Fix:

  • Run the class with the full package path:
java com.example.MainClass  
  • Rebuild the executable JAR with a valid manifest (see how to create executable JARs).

5. ArrayIndexOutOfBoundsException

Error Message:
java.lang.ArrayIndexOutOfBoundsException

Cause:
Accessing an array index that doesn’t exist (e.g., index 5 in an array of size 5).

Example:

int[] numbers = {1, 2, 3};  
System.out.println(numbers[3]); // Valid indices are 0-2  

Fix:

  • Loop safely using array.length:
for (int i = 0; i < numbers.length; i++) { ... }  

6. UnsupportedClassVersionError

Error Message:
java.lang.UnsupportedClassVersionError: Unsupported major.minor version 61.0

Cause:
The Java class was compiled with a newer JDK but is running on an older JRE.

Fix:

  • Update the JRE to match the JDK version used for compilation.
  • Recompile the class with an older target version:
javac -target 8 -source 8 MyClass.java  

7. NoSuchMethodError

Error Message:
java.lang.NoSuchMethodError

Cause:
A method is called that doesn’t exist in the loaded class version (common in dependency conflicts).

Fix:

  • Check dependency versions in your build tool (Maven/Gradle).
  • Run mvn dependency:tree to identify conflicting libraries.

8. OutOfMemoryError

Error Message:
java.lang.OutOfMemoryError: Java heap space

Cause:
The application uses more memory than allocated to the JVM heap.

Fix:

  • Increase heap size using JVM arguments:
java -Xmx2048m -Xms512m MyApp  
  • Optimize code to reduce memory leaks (e.g., avoid unnecessary object creation).

9. “Exception in thread main” (Generic Runtime Errors)

Example:
Exception in thread "main" java.lang.ArithmeticException: / by zero

Fix:

  • Add error handling with try-catch blocks:
try {  
    int result = 10 / 0;  
} catch (ArithmeticException e) {  
    System.out.println("Cannot divide by zero!");  
}  

10. “javac is not recognized” (Compilation Error)

Cause:
Java Development Kit (JDK) is not installed or not added to the system PATH.

Fix:

  • Install the JDK from Oracle’s website.
  • Add Java to the PATH variable:
    • Windows: Go to System Properties > Environment Variables > Path > Add JDK bin path.
    • Linux/macOS: Update ~/.bashrc or ~/.zshrc with export PATH=$PATH:/path/to/jdk/bin.

Tips for Handling Common Errors in Java

Use specific exception classes

When we throw an exception, specify the most specific exception class that we can. This will give the caller of our method more information about what went wrong, and it will make it easier for them to handle the exception.

For example, if we are trying to read a file that does not exist, we would throw a FileNotFoundException instead of a generic Exception. This will let the caller know exactly what went wrong, and they can take appropriate action.

Example:

try {
    File file = new File("myfile.txt");
    Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
    // Handle the exception.
    System.out.println("File not found: " + e.getMessage());
}

Log exceptions

Even if we’re able to handle an exception gracefully, it’s still a good idea to log it. This will help us track down the source of the error and prevent it from happening again.

There are many different logging frameworks available for Java. We can use whichever one we prefer.

Example:

try {
    File file = new File("myfile.txt");
    Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
    // Log the exception.
    Logger logger = Logger.getLogger("myapp");
    logger.error("File not found: " + e.getMessage());
}

Don’t swallow exceptions

If we’re not able to handle an exception, we should not just swallow it. Swallowing an exception means that we’re ignoring it. This can lead to problems later on. Instead, we can rethrow the exception so that the caller of our method can handle it.

Example:

try {
    // This code might throw an exception.
} catch (Exception e) {
    // Don't swallow the exception.
    throw e;
}

Use finally blocks

Finally blocks are executed no matter what happens in the try block. This makes them a good place to clean up resources, such as files or database connections.

Example:

try {
    // This code might throw an exception.
} finally {
    // Close the file, even if an exception was thrown.
    File file = new File("myfile.txt");
    file.close();
}

Use try-with-resources

Try-with-resources is a new feature added in Java 7 that makes it easier to close resources. When we use try-with-resources, the resources are closed automatically at the end of the try block, even if an exception is thrown.

Example:

try (FileInputStream inputStream = new FileInputStream("myfile.txt")) {
// This code will not throw an exception if the file is closed.
}

By following these tips, we can handle common Java errors gracefully and prevent them from causing problems in our applications.

Troubleshooting Tips for Java Errors

  1. Read the Stack Trace: The error message often points to the exact line and class causing the issue.
  2. Google the Error: Developers worldwide have likely faced (and solved) the same problem.
  3. Use Debuggers: IDEs like Eclipse and IntelliJ have built-in debuggers to step through code.
  4. Check Dependencies: Mismatched library versions cause many runtime errors.

Additional Tips

  • Use a consistent error handling style throughout our code. This will make it easier for us and other developers to understand yur code and handle errors.
  • Use a logging framework to log exceptions. This will help us track down the source of errors and prevent them from happening again.
  • Testing our code thoroughly to make sure that it handles errors gracefully.

Final Thoughts

Java errors are frustrating but solvable with systematic debugging. Bookmark this guide for quick fixes, and explore our tutorials on running JAR files and creating executable JARs to master Java deployment.

Still stuck? Drop a comment below, and we’ll help you troubleshoot!

Related Posts:

  • Compile and Run Java Program
  • Control Statements in Java
  • Install and Set Up Java Development Environment
  • What Is Java Swing? A Complete Guide to Java’s GUI Toolkit
  • Exception Handling Keywords in Java
  • Suppressed Exceptions in Java
Tags:java
Was this article helpful?
← Previous ArticleHTTP Methods
Next Article →JDBC Best Practices: Writing Robust and Efficient Database Code

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
  • Complete Guide to JaCoCo: How to Measure Java Code Coverage Accurately
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap