DockYard
DockYard

Reputation: 1040

Getting java.lang.ClassNotFoundException when using package

I have a java file ComPac.java with the below code:

package com;
public class ComPac{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

The file is located at the path : /home/ec2-user/java_c

To compile this file, I ran javac Compac.java, and the class file was generated.

enter image description here

Now its turn to run the class file.

So I did java ComPac(screenshot below)

java ComPac

Understandably, I got the error Error: Could not find or load main class ComPac. Caused by: java.lang.NoClassDefFoundError: com/ComPac (wrong name: ComPac). This I am assuming is because the java file has the package com declared in it.

So instead I tried, java com.ComPac and expected it to work(screenshot below).

java com.ComPac

But I got the error: Error: Could not find or load main class com.ComPac. Caused by: java.lang.ClassNotFoundException: com.ComPac.

So how do I run this? and what exactly is the logic for running when it comes to packages in java?

Java used- openjdk version "11.0.8" 2020-07-14 LTS(AWS Corretto)

OS used- Amazon Linux 2

Upvotes: 1

Views: 1456

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

The correct way of doing it as follows:

javac -d . ComPac.java

The switch -d . asks the compiler to place generated class files at the current directory as . stands for the current directory. Learn more about the switches by simply using the command javac

Now, if you use the command ls in Mac/Unix or dir in Windows, you will see a directory, com has been created and ComPac.class has been placed inside this directory. In order to execute the class, you can now use the following command:

java com.ComPac

Upvotes: 2

Dupinder Singh
Dupinder Singh

Reputation: 7789

If you are using Java 11 then you don't need to first compile java file and then run the class file. You can directly run the java file using just

java .\test.java

test.java

package com;

public class test{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

command:

java .\test.java

Output:

Hello World

Upvotes: 3

Chris
Chris

Reputation: 176

put the class in a folder called "com"

in a bash shell it's then:

$ java com/ComPac

(from the folder containing "com", not inside of "com")

Upvotes: 5

Related Questions