Currently a beginner to Java
and I have the extension Code Runner
installed. I am able to run my code within the window via the Run | Debug
options provided by Code Runner
. However, after compiling the file with javac
, I am unable to run the file. This is the basic code inside a filepath CommandLineApp/HelloWorld.java
.
package CommandLineApp;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world..!!!");
}
}
After I cd
into CommandLineApp, I ran
javac HelloWorld.java
java HelloWorld
which gives me this error
Error: Could not find or load main class HelloWorld
Caused by: java.lang.NoClassDefFoundError: CommandLineApp/HelloWorld (wrong name: HelloWorld)
Apologies if this is a really simple question!
You don't cd
to the package directory, i.e. CommandLineApp
. You cd
to the parent directory of the package directory. And you give the fully qualified name when you launch the class, i.e:
java CommandLineApp.HelloWorld
Alternatively, you use the -classpath
option in the java
command, i.e:
java -cp dir CommandLineApp.HelloWorld
where dir
is the path to the parent directory of CommandLineApp
.
Perhaps this tutorial will help.
Note that, since JDK 11, you can also launch a Java source code file. Refer to the documentation.
By the way, according to Java naming conventions, the package name should be something like commandlineapp
or commandline.app