Difference Between PATH and CLASSPATH in Java



In Java, the terms Path and ClassPath refer to different things and are used for different purposes. Let's discuss them one by one with a suitable example ?

Path

The path environment variable is used to specify the set of directories that contains execution programs.

When you try to execute a program from the command line, the operating system searches for the specified program in the current directory and, if available, executes it.

In case the programs are not available in the current directory, the operating system verifies in the set of directories specified in the 'PATH' environment variable.

Setting the path

set PATH=%PATH%;C:\Program Files\Java\jdk-11\bin

Example

When you type javac to compile a Java program, the system uses the path to find the javac.exe executable ?

import java.io.File;
public class Helloworld{
    public static void main(String[] args) {
	   System.out.println("Hello World!");
    }
}

Output

Following is the output of the above program ?
Hello World!

ClassPath

The ClassPath environment variable is used to specify the location of the classes and packages where the JVM looks for user-defined classes and packages.

When we try to import classes and packages other than those that are available with the Java Standard Library.

JVM verifies the current directly for them; if not available, it verifies the set of directories specified in the 'CLASSPATH' environment variable.

Setting ClassPath

java -cp ".;lib/*" MyApp

Here, the MyAPP is a project name, can be any name

Example

To verify the ClassPath, we create a project in Java with any name ( such as MyApp), and within the src/main/java folder we create a package named "com.example" (user defined package). Within this package will define a class with the name MyApp (entry point) and place the below code ?

package com.example;

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

To run the above code using classPath use the following command ?

javac -d bin src/main/java/com/example/MyApp.java 

The above command compiles your Java source file and places the compiled class files in a specified output directory.

java -cp "bin;lib/*" com.example.MyApp

The above code runs the specified class located in the given package.

Output

Following is the output of the above program ?
Hello World!
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2024-12-17T23:03:52+05:30

980 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements