0

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!

Jun Han
  • 13,821
  • 7
  • 26
  • 31
Peek0
  • 173
  • 2
  • 9

1 Answers1

2

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

Abra
  • 19,142
  • 7
  • 29
  • 41
  • Thank you so much! I was following a tutorial that glossed over this and used a Code Runner, but I missed the part where he was not CD into the folder. Really appreciate entertaining such a basic question! – Peek0 Dec 06 '22 at 01:20