How to Set Classpath in Java?
CLASSPATH describes the location where all the required files are available which are used in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw the following error.
Error: Could not find or load main class <class name> (e.g. GFG)
The above error is resolved when CLASSPATH is set.
// If the following code is run when the CLASSPATH is not
// set, it will throw the above error.
// If it is set, we get the desired result
import java.io.*;
class GFG {
public static void main(String[] args)
{
// prints GeeksForGeeks to the console
System.out.println("GeekForGeeks!");
}
}
Output
GeekForGeeks!
Set the CLASSPATH in JAVA in Windows
Command Prompt:
Open the Command Prompt.
Use the following command to set the CLASSPATH:
set CLASSPATH=.;C:\path\to\your\classes;C:\path\to\your\librariesNote: The dot (.) represents the current directory, and the semicolon (;) is used as a separator between different paths.
Example:
set CLASSPATH=.;C:\Users\GFG\JavaClasses;C:\Program Files\Java\libsGUI:
1. Select Start
2. Go to the Control Panel

3. Select System and Security

4. Select Advanced System settings

5. Click on Environment Variables

6. Click on New under System Variables

7. Add CLASSPATH as variable name and path of files as a variable value.

8. Select OK.
Set the CLASSPATH on Linux
Command Line:
Find out where you have installed Java, basically, it's in /usr/lib/jvm path. Set the CLASSPATH in /etc/environment using
sudo <editor name> /etc/environment
Add the following lines,
CLASSPATH=".:/path/to/your/classes:/path/to/your/libraries"
export CLASSPATH
Note: Colon (:) is used as a separate directory and dot (.) is the default value of CLASSPATH in the above command.
To check the current CLASSPATH, run
echo ${CLASSPATH}
Difference between PATH and CLASSPATH
- The PATH variable is used to specify the location of the Java binaries (e.g., java, javac). It allows the system to locate the Java executables to compile and run programs.
- The CLASSPATH variable is used to specify the location of the Java class files and libraries required for the program. It tells the JVM and compiler where to look for user-defined classes and packages.
Conclusion
Properly setting the CLASSPATH is crucial for the Java compiler and JVM to locate the required class files and libraries necessary for compiling and running your Java applications. Understanding the difference between the PATH and CLASSPATH is essential, as each serves a distinct purpose. While PATH points to the location of Java executables like javac and java, CLASSPATH is used to specify the locations where the class files or libraries are stored. A correctly configured CLASSPATH ensures that your Java programs run smoothly without errors related to missing class files.