Issue
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.
Now its turn to run the class file.
So I did java ComPac
(screenshot below)
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).
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
Solution
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")
Answered By - Chris
Answer Checked By - Timothy Miller (JavaFixing Admin)