Search code examples
javajavac

Cannot run java class from command line


I created a package in Eclipse and ran my HelloWorld just fine from Eclipse.

When I went to a command prompt and navigated to that folder and ran javac HelloWorld.java, it compilied without issue.

When I ran java HelloWorld, I got Error: Could not find or load main class HelloWorld

I also tried java Hello.HelloWorld thinking that it might be because it had a package declaration

package Hello; 
public class HelloWorld { 
    public static void main(String[] args) { 
       System.out.println("Hi there. How you doin?");
   } 
}

Solution

  • When you run javac, use the switch -d to specify that you would like to create the folder structure for package. javac reference.

    E.g. javac -d . HelloWorld.java

    When you say -d ., compiler creates the classes with package directory structure in the current path.

    Once you have the compiled classes, use java Hello.HelloWorld to run the program.

    Suggests you to start the package name with lower case.