0

I am a beginner and am setting up my java on windows 10 following the instruction of cs61b

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

After I compiled it with javac HelloWorld.java, I ran java HelloWorld but it reported an error:

Error: Could not find or load main class HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld

Instead, java HelloWorld.java works. I wonder how to fix that problem? Thanks!

Here is the screenshot of the problem shown on my Git Bash

papanito
  • 2,349
  • 2
  • 32
  • 60
Vincent.Z
  • 11
  • 1
  • What is the content of your CLASSPATH setting/variable? – Progman Aug 29 '20 at 10:28
  • My class path is: %JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar The JAVA_HOME variable is C:\Program Files\AdoptOpenJDK\jdk-14.0.2.12-hotspot\ – Vincent.Z Aug 29 '20 at 23:20
  • I install Java by installing Java OpenJDK 14 (HotSpot JVM). AndI just notice that I have already Java 12 in my windows 10. Should I uninstall Java 12? – Vincent.Z Aug 29 '20 at 23:26

2 Answers2

2

Try java -cp . HelloWorld. With compiled files you have to specify the classpath where your classes are. Then you tell the class where your main method is.

The java HelloWorld.java is working because you are probably using Java 11+

How to execute a java .class from the command line

sergiomse
  • 775
  • 12
  • 18
  • Thanks! It works! But I I installed Java OpenJDK 14 (with HotSpot JVM) and I think 'javac HelloWorld' should work, as the bottom of this instruction page shows [link](http://fa20.datastructur.es/materials/lab/lab1setup/lab1setup). I don't know what caused my problem. I just notice that I have a Java 12 previously installed in my computer. Is that a possible cause? – Vincent.Z Aug 29 '20 at 23:42
1

My problem is solved when I add ".;" in the beginning of the CLASSPATH. Thanks!

Vincent.Z
  • 11
  • 1