Korsarq
Korsarq

Reputation: 795

Could not find or load main a class in Java

i have the following project structure:

JavaTest
    Main
        Main.java
    Test
        Test.java

Main.java:

package Main;
import Test.*;
public class Main {
    public static void main(String[] args) {
    }
}

Test.java:

package Test;
public class Test {
} 

I compile them with the following commands:

D:\Development\Workspace\JavaTest>javac Main\Main.java

D:\Development\Workspace\JavaTest>javac Test\Test.java

The class files are put like this:

JavaTest
    Main
        Main.java
        Main.class
    Test
        Test.java
        Test.class

I'm trying to run it with the following command:

D:\Development\Workspace\JavaTest>java -cp D:\Development\Workspace\JavaTest\Main;D:\Development\Workspace\JavaTest\Test Main

The error i'm getting is:

Error: Could not find or load main class Main
Caused by: java.lang.NoClassDefFoundError: Main/Main (wrong name: Main)

Upvotes: 1

Views: 4238

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79560

Do it as follows:

javac -d . Main/Main.java
java Main.Main

Notes:

  1. The current directory is represented by a .
  2. I recommend you follow the Java naming convention. As per the naming convention, the name of your package should be main. Check https://www.oracle.com/technetwork/java/codeconventions-135099.html for more details.
  3. Use the command, javac -help to know more about the options available with javac.

Upvotes: 1

Abacus
Abacus

Reputation: 19471

add the package to your main class and set the classpath to the base directory

D:\Development\Workspace\JavaTest>java -cp D:\Development\Workspace\JavaTest Main.Main

I'd recommend you stick to Java conventions and use only lowercase names in your package. And you don't need the Test path to run your class

Upvotes: 3

Related Questions