Search code examples
javaclassnotfoundexception

Exception in thread "main" java.lang.NoClassDefFoundError launch error


I have the typical error in Java. I have the next structure:

bin/
lib/
src/
   junior/
         databases/
                  homework/Main.java

My Main.java code is:

package junior.databases.homework;

import java.sql.*;

public class Main {
    private static Connection connection = null;

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        initDatabase();
        System.out.println("Done");
    }

    private static void initDatabase() throws SQLException, ClassNotFoundException {
        Class.forName("org.postgresql.Driver");

        connection = DriverManager.getConnection(
                    "jdbc:postgresql://192.168.136.129:5432/postgres", "postgres", "xxxx");
    }
}

When I launch it like this:

root@debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src/junior/databases/homework# javac Main.java
root@debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src/junior/databases/homework#java Main

I got error:

Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: junior/databases/homework/Main)

I found in this post the solution Exception in thread "main" java.lang.NoClassDefFoundError: Hello

And my try:

root@debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src# javac junior/databases/homework/Main.java
root@debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src# java junior.databases.homework.Main

works perfectly. The problem is I can launch this code only from src/ folder((( Is there any way I can launch it from /src/junior/databases/homework folder? I need to go back to src each time I want to launch the code.


Solution

  • Here you are, assuming you are in src/junior/databases/homework directory:

    javac ../../../junior/databases/homework/Main.java
    java -cp ../../../ junior.databases.homework.Main