What is PATH and CLASSPATH in java and why do we need it?

Which environment variables do I need to set on my machine in order to be able to run Java programs?

or

Difference between PATH and CLASSPATH?

PATH and CLASSPATH are the most important and basic environment variables which are used to compile and execute a java program. 

First let us discuss about the PATH.

PATH is an environment variable which will point to the JDK binaries like "javac", "java" and "javap" commands.

"javac" command is used to compile the java program and the "java" command is used to run/execute the java program.

If you have installed java in your system you can view where these commands exists, and that location is the 'PATH' variable in your system.



So to simplify, PATH specifies the location where the exe files like java.exe, javac.exe, appletviewer.exe, javap.exe exists.      

You can use the below Command to set PATH in Windows

set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_281\bin

If you don't set the PATH, you need to specify the full path where the javac exe file exists to compile the java program.

Now let us discuss about the ClassPath:

CLASSPATH is another environment variable used by the java compiler. This CLASSPATH specifies the location where the class files exists. These class files are bundled as the jar files. 

For example if your java program is using "String" class, where does the java compiler verifies whether this String class exists or not. Basically this "String" class file is bundled in the rt.jar and our classpath will be pointing to the location where this rt.jar exits.

set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\Jre1.8.0_281\lib

To simplify, path variable is used to set the path to the exe files like javac and java and classpath represents the location of the java classes which are needed to compile your java file.

Comments