Java.What is the classpath in java ?

The classpath in Java is a parameter that tells the JVM where to look for user-defined classes and resources when running a Java application. It defines the locations of .class files and JARs needed by the program.

How Does Classpath Work?

  • When you run a Java program, the JVM needs to find and load all required classes.
  • It searches for classes in the classpath directories or JAR files.
  • If a class is not found in the classpath, a ClassNotFoundException or NoClassDefFoundError occurs.

Default Classpath

  • If you don’t specify a classpath, the JVM defaults to the current directory (.).
  • Example:shCopyEdit
java MyClass

Here, java looks for MyClass.class in the current directory.

Setting the Classpath

1. Using the -cp or -classpath Option

  • You can specify the classpath when running a program:
java -cp /path/to/classes MyClass

If using multiple locations, separate them:

  • Windows: Use ; as a separator:
java -cp .;C:\libs\myLib.jar MyClass

Linux/macOS: Use : as a separator:

java -cp .:/home/user/libs/myLib.jar MyClass

2. Using the CLASSPATH Environment Variable

  • You can set a global classpath using the CLASSPATH environment variable.

Windows (Command Prompt)

set CLASSPATH=C:\myapp\lib\myLib.jar;.

Linux

export CLASSPATH=/home/user/myapp/lib/myLib.jar:.

Note: Setting CLASSPATH globally is not recommended because it can interfere with other applications.

Classpath with JAR Files

  • To include multiple JAR files in the classpath:
java -cp "lib/*" MyClass

his includes all JAR files inside the lib/ directory.

Example with JAR files:

java -cp myApp.jar:lib/dependency1.jar:lib/dependency2.jar MyClass

lasspath vs. Module Path (JDK 9+)

  • Classpath: Used in traditional Java applications.
  • Module Path (--module-path): Introduced in JDK 9 for the Java Module System.

For modular applications, use:

java --module-path mods -m my.module/com.example.Main

Key Takeaways

  1. Classpath tells the JVM where to find .class files and JARs.
  2. Default classpath is the current directory (.).
  3. You can specify the classpath using:
    • The -cp or -classpath option.
    • The CLASSPATH environment variable.
  4. In JDK 9+, --module-path is used instead of classpath for modular applications.
  5. Incorrect classpath settings can cause ClassNotFoundException.
This entry was posted in Без рубрики. Bookmark the permalink.