3 ways to solve Eclipse - main class not found error

Like many Java programmers who get "Error: Could not find or load main class Main" while running the Java program in Eclipse, I was also getting the same problem recently. The "Error: Could not find or load main class" was rendered me puzzled even after my 10+ years of experience with Java errors and exceptions. Whenever I run my Java application either by Run configurations or right-click and run as a Java program, I get an annoying popup complaining about "could not find or load the main class, the program will exit". 

I further checked, the project was compiling fine, I can see the .class file for the main class in the bin directory of Eclipse, and I can even see the project and output folder added on the classpath of Run configuration, but still, I am getting the "could not find main class, the program will exit error".

I spent good two hours trying everything I could, calling teammates for help (getting an extra pair of eyes always helps in this kind of situation),   searching on the internet, and lots of trial and error, but the error was persistent. 

The first clue I got when I debug my Java program. I debug the Java application in Eclipse by right click and choose "Debug As Java program" and found that it was throwing ClassNotFoundEexception for a third-party class.

It was a kind of breakthrough after wasting such a long time but still, the clue wasn't enough because the class belongs to one of the dependent JAR which was available in classpath but somehow Eclipse was not seeing it. 

My error was resolved after deleting the existing run configuration where the User entry was not pointing to the default classpath. Just deleting the run configuration and re-creating it by running the class by right click, "Run As Java program" will fix the error.




Solution of Error: Could not find or load main class in Eclipse

Even though I managed to solve the problem but it was too much trouble for me and taken a lot of time. I don't want to face the same situation again, especially if I am urgent to run my Java program to debug an urgent production issue. 

Hence, I have decided to jot down my experience with a couple of more tricks from the past. In this article, I'll share three useful tips to solve the "could not find or load main class error" in Eclipse. 


1. Delete existing run configurations

When you run the main class as "Run as Java Program", it adds the default classpath of the project as User entries into Run Configurations's classpath as shown below.

"Error: Could not find or load main class Main"  solution in Eclipse


The problem in my case was that my project also needed native libraries and due to other errors, I have been fiddling with classpath. It seems while creating the run configuration by copying from another project, I deleted the old project with the default classpath and added a new project without the default classpath. 

This caused the problem as Eclipse was not detecting any dependent JAR in the project. The problem was obscured by the error because it always complains about the main class not found, similar to the annoying popup below:

How to fix main class not found error in Eclipse


Remember, if your main class is dependent upon any other class or JAR file and if you believe everything in the classpath, then just delete the Run configurations and Run the main class as a Java program and then edit the run configuration. This solved the problem in my case. You can further check out these free Java Programming Courses to learn more about classpath and how JVM search and load class files.

Also, some of you might not be getting this popup because I got the popup only on Eclipse Kepler but when I tried to reproduce the issue in "Eclipse IDE for Java developers" on Eclipse Luna, I just got the "Error: Could not find or load main class Main" in red and bold.


2. Check for missing library

If you see a red exclamation mark in your project means some of the libraries which are added in the build path are either deleted or moved to another location. Until you fix this issue, your project will not compile and no class is created in the bin directory, hence when you run your Java program, Eclipse's classloader will not find the main class and throw this error.

Here is how your project will look like if any library from the build path is missing due to any reason like somebody copied to another directory or you close the project from which they were added.


Eclipse Error: Could not find or load main class solution

To  solve this problem just follow the below steps:
  • Go to configure build path
  • Check which JAR is missing
  • Remove them and add them to the new location. 
You can further join these Eclipse online courses to learn more about setting and building Java projects in Eclipse.



3. Debug the Java program

This will tell you exactly which class is missing in the class path. I mean if your main class is referring to another class from a third-party library and that library is not in the classpath, Eclipse will throw the same "main class not found error". When you run the program in debug mode, you can see exactly which class the program is not able to found.

Here is how the debug configuration looks like, you just need to click the debug to start debugging your program, the JVM will start automatically if it's not able to find the main class and print the actual class and error in the console.

How to solve main class not found error in Eclipse


There were a couple of more reasons for "Error: Could not find or load main class Main" in Eclipse. I'll slowly add those as well. If you want to help you can put your problem and solution related to Eclipse main class not found error and I'll add those reasons in the main posts. I intend to make this post my go-to place whenever I get the ClassNotFoundException or NoClassDefFoundError in Eclipse to avoid wasting more time in the future.


Other Eclipse tutorials and tips for Java developers
  • How to connect Eclipse to the Oracle database? (see here)
  • How to make an executable JAR file in Eclipse? (see here)
  • How to increase the heap size of the Java program running in Eclipse? (see here)
  • How to fix Unsupported major.minor version 52.0 error in Eclipse? (see here)
  • 3 Maven Eclipse tips for Java developers (see here)
  • Top 30 Eclipse keyboard shortcuts  for Java programmers (see here)
  • How to setup remote debugging in Eclipse (see here)
  • How to attach source code for the JAR file in Eclipse for debugging? (see here)
  • How to fix maven dependency search not working in Eclipse? (solution)
  • 3 Books to learn and master Eclipse IDE for Java programming (books)

19 comments:

  1. Unfortunatelly none of these methods worked in my case...
    I also created a new Project, created in it every "Source Folder"s and copyed my packages from my not-working project to the corresponding new packages of my new project. But it thowed even the same error...

    ReplyDelete
  2. I spent tenths of hours trying to solve this, and what only helped me at the end was to notice that I had in my packages some files (text files) with the same name, like TODO, README and IMPORTANT. I went through every package of my project renaming those files (like TODO_packagename1, TODO_packagename2...) and when finished, I closed Eclipse and restarted it again. Then worked!

    ReplyDelete
  3. Can't find words to thank you. That error was eliminated. Later it got stuck elsewhere but this was really helpful. Thanks a ton! :)

    ReplyDelete
  4. Hi Javin,


    package com.hello;

    public class HelloWorld
    {

    /**
    * @param args
    */
    public static void main(String[] args)
    {
    // TODO Auto-generated method stub
    System.out.println("Hello World");
    }

    }



    Hi, I am getting below error

    Error: Could not find or load main class

    for above java code while running,
    When, I do the debug
    There is 2 exception
    As ClassCastException, FileNotFoundException
    I am not able to resolve above exception, as I am clueless Why it is so,
    As It is simple java program.

    Could you please help me.

    Thanks



    ReplyDelete
    Replies
    1. Hello Anonymous, did you put the class inside com/hello directory? If not then just remove the package declaration from above code and it will run fine.

      Delete
  5. import java.sql.*;
    class Mysql{
    public static void main(String args[]){
    try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/sonoo","root","root");
    //here sonoo is database name, root is username and password
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("select * from emp");
    while(rs.next())
    System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
    con.close();
    }catch(Exception e){ System.out.println(e);}
    }
    }





    this is the above i want to run in eclipse oxigen but i am getting error as "could not find or load main class"

    ReplyDelete
  6. Your First point was helpful in resolving the issue. Thank you

    ReplyDelete
  7. Thanks, deleting existing run configuration solved the problem.

    ReplyDelete
  8. i have execute the program and no errors in program but program is run then get the error is could not load main class

    ReplyDelete
  9. Simply, go to Projects and click clean. Clean your project once, it started working for me! Hope it helps you the best.

    ReplyDelete
    Replies
    1. yes, sometime that works, check if you clicked the "Build Automatically" option as well, this means it will automatically build your project if there is a change.

      Delete
  10. Thank you so much
    I check configure build path and a library was missing

    ReplyDelete
  11. Sorry sir.I cannot solve this problem.
    Please tell me sir.I am beginner.Please help me sir.

    ReplyDelete
    Replies
    1. Hello Anonymous, can you provide more detial? what is happenign, error messages what have you tried so far etc.

      Delete
  12. This was so silly. I was getting the exception despite having correct entry point configured in pom.xml.

    In my case this error was occurring because I forgot to mention "string[args]" in main method arguments,

    ie I had written - public static void main() --- INCORRECT Instead Of public static void main (String args[]) -- CORRECT

    ReplyDelete
  13. i found signature of main class was deviated from psvm(Strings[] args) to psvm(String args),after corrected its resolved

    ReplyDelete
  14. public class SuperPower {
    public static void main(String[] args)
    {
    System.out.println("SUPER POWERS TO THE RESCUE!");
    }


    }

    Output (console):

    Error: no se ha encontrado o cargado la clase principal SuperPower
    Causado por: java.lang.ClassNotFoundException: SuperPower


    Hello, Javin!

    I am receiving this error message when I try to run my program. Can you tell me how can I correctly run my program?

    Thanks...

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.