javawindowscmdconsolesystem-variable

Java "Could not find or load main class" (PATH and CLASSPATH Already Set)


I'm having issues running java on the command line. I have checked lots of other questions and none have solved my problem.

I am using Windoze 10 x64.

Installed at C:\Program Files\Java, I have the following files:

jdk1.8.0_121 and jre1.8.0_121.

I already set the JAVA_HOME, PATH and CLASSPATH as follows:

This is the current configuration of the system variables. I tried lots of variations for the configs but none seem to help. Such as adding to the PATH %JAVA_HOME%\jre1.8.0_121\bin as well. Nothing seems to help.

If I run java -version and javac -version they will go through, showing the current version installed.

I can also compile, for example: javac HelloWorld.java succesfully.

When I try java HelloWorld, I get Could not find or load main class HelloWorld.

Here is the HelloWorld.java file:

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

I spent +2 hr trying to figure this out. I'm sure it's a rookie mistake but honestly, I'm just trying to set this up so I can start learning Java.

I can run java using IntelliJ IDEA Community Edition's console but not directly on CMD.

I would really appreciate if you could walk me through like LI5, I really looked for the solution, watched videos on how to set the system variables but it yield nothing.

If you need any more information I'm happy to provide it, thank you.


EDIT: Okay, the issue was solved. Thanks to @azurefrog and @mirmdasif for helping me figure it out.

As you can read Hereand below this on azurefrog's comments and mirmdasif's reply, you need to add the current working directory to the CLASSPATH.

Add the current working directory to the CLASSPATH by adding a .(dot) to the CLASSPATH.

So CLASSPATH should look like this instead: .;%JAVA_HOME%/lib (Notice the . followed by the semi-colon ;.


Solution

  • The problem is with your CLASS_PATH variable.

    The preferred way to specify the classpath is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications

    Default value for ClassPath variable is '.' which means only the current directory is searched. If you specify the classpath variable the default will be overridden.

    If want to set classpath as environment variable you may do as running the following cmd in cmd prompt(remember the dot in the beginning)

    C:> set CLASSPATH=.;C:\Program Files\Java\jdk1.8.0_121\lib\*
    

    For further information http://docs.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html