Course contentsShow
← Java
Lesson 691 of 2,87016. Packages, Imports, and JAR FilesFree lesson

The CLASSPATH Environment Variable

Setting the CLASSPATH environment variable as an alternative to -cp, understanding precedence, and why -cp is generally preferred.

The CLASSPATH Environment Variable

You'll learn how to set CLASSPATH globally and why the -cp option is usually better.

In the previous lesson, you used the -cp or -classpath option to tell Java where to find classes at runtime. There's another way: setting the CLASSPATH environment variable on your system. This acts as a default search path that Java uses whenever you don't specify -cp.

How It Works

The CLASSPATH environment variable is a system-level setting. Once configured, every java command automatically uses it to locate classes and JAR files—unless you override it with -cp.

Setting it varies by operating system:

  • Windows (Command Prompt):

    set CLASSPATH=C:\libs\mylib.jar;C:\classes
    
  • macOS/Linux (Bash):

    export CLASSPATH=/libs/mylib.jar:/home/user/classes
    

Use semicolons (;) on Windows, colons (:) on Unix-like systems to separate multiple paths.

Understanding Precedence

When you run java MyClass:

  1. If -cp is specified: Java uses that path exclusively and ignores CLASSPATH
  2. If -cp is not specified: Java uses the CLASSPATH environment variable
  3. If neither exists: Java only searches the current directory

The -cp option always wins.

Why -cp Is Generally Preferred

  • Explicitness: Each command shows exactly which classpath it uses
  • Project isolation: Different projects can have different dependencies without conflicts
  • No surprises: Forgetting about a global CLASSPATH can cause mysterious bugs
  • Build tools handle it: Maven, Gradle, and IDEs manage classpaths automatically

Setting CLASSPATH globally is convenient for quick experiments but risky for production work. A stale or incorrect CLASSPATH can break multiple projects silently.

Key Takeaway: The CLASSPATH environment variable provides a default class search path, but the -cp option overrides it and is preferred for its explicitness and project isolation.