What is classpath vs module path in Java?

In Java, the classpath and the module path are two mechanisms used to specify where the Java Runtime Environment (JRE) should look for classes and packages. The main differences between them include how they handle dependencies and modules.

Classpath

The classpath is a legacy mechanism that has been used since Java's inception. It tells the Java Virtual Machine (JVM) where to find user-defined classes and packages in Java programs. The classpath can include directories, JAR files, and ZIP files. It is particularly used in projects that do not use Java 9's module system.

Module Path

The module path, introduced in Java 9 as part of the Java Platform Module System (JPMS), allows the use of modules. Modules can encapsulate packages and manage dependencies more effectively than the traditional classpath. This makes the module path particularly useful for larger applications where modularity and dependency control are essential.

Key Differences

  • Structure: Classpath is a flat structure, while the module path organizes classes into modules.
  • Encapsulation: Modules prevent exposure of implementation details which is not possible with the classpath.
  • Dependency Management: The module system provides strong encapsulation and dependency management, reducing runtime errors related to classpath dependencies.

Example

// This is a Java example of setting up classpath and module path // Setting Classpath java -cp "lib/*:." com.example.Main // Setting Module Path java --module-path lib --module com.example.Main

classpath module path Java classpath Java module path JVM JPMS Java dependencies