Search code examples
javaclassclassnotfoundexception

Java Error: Could not find or load main class (ClassNotFoundException)


I have a java file hello.java

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

I entered javac hello.java command to compile it and successfully generated a .class file in the same path hello.class (decomplied version)

 // Source code is unavailable, and was generated by the Fernflower decompiler.
public class hello {
   public static void main(String[] var0) {
      System.out.println("Hello World");
   }
}

However when I try to run the main function for hello class with the command java hello, it always turn out to throw a ClassNotFoundException

PS D:\Study\JAVA> java hello
Error: Could not find or load main class hello

When I tried internal debug feature of VS Code, the main function worked normally so I can confirm that the function inside has no error.

I can also confirm the class name I applied in my command completely correct. I dont understand why this ClassNotFoundException always show up.

I know it's just a very basic question (maybe stupid). Many thanks for any possible answer.

I'm using java 1.8.0_311

I compiled the java file with javac hello.java and it works normally. Then I can see a java class file - hello.class has been generated. I tried many times to run java hello but always get ClassNotFoundException. I have tried restarting the IDE or delete and rewriting the whole file but none of them works.


Solution

  • Doing exactly that works for me (on Linux). However, I don't have java installed on Windows to test.

    You can try java -cp . hello which will explicitly set the classpath to the current directory, which should allow java to find the class.