javapathenvironment-variablesclasspath

different views for setting class path for java program


I am trying to run my simple java program via command prompt. While compiling the code there is no error. But every time I execute the program, I get the same error,

C:\Users\anapi>javac simple.java

C:\Users\anapi>java Simple.class
Error: Could not find or load main class Simple.class
C:\Users\anapi>java -cp . Simple.class
Error: Could not find or load main class Simple.class

I searched in net for the solution, and there are many solutions provided. But none of them worked for me. So I've posted here for the help. I know the problem is due to class path and I tried the possible solutions too but none of them worked. Please check my JAVA configurations details.

C:\Users\anapi>java -version
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) Client VM (build 25.101-b13, mixed mode)

C:\Users\anapi>javac -version
javac 1.8.0_101

C:\Users\anapi>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.8.0_101

C:\Users\anapi>echo %PATH%
C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.8.0_101\bin;C:\Program Files\Java\jre1.8.0_101\bin

C:\Users\anapi>echo %CLASSPATH%
.C:\Program Files\Java\jdk1.8.0_101\bin;

My code:

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

Please help me I am badly stuck in this problem.


Solution

  • Use the command as ::

    C:\Users\anapi>java Simple
    

    Also note that if you are using Eclipse and want to compile and execute your code from command prompt then follow the following steps::

    1. Suppose your java file is simple.java inside [C:\Users\anapi\workspace\test],

    for compiling the code ::

    C:\Users\anapi\workspace\test>javac C:\Users\anapi\workspace\test\src\test\simple.java
    

    and for executing the code ::

    C:\Users\anapi\workspace\test>java -cp bin test.Simple
    

    You can get the class path of the source file by running the program in debug mode. After that, in the upper left tab [Debug], right click on your terminated program and go to Properties. There in the Command Line box you can see the classpath. Paste the classpath with java command in command prompt.

    C:\Users\anapi>java -classpath C:\Users\anapi\workspace\FirstProject\bin test.HelloWorld
    

    enter image description here