Java Tool Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 5.00

Option "-classpath" - Specifying Class Path

This section provides a tutorial example on how to use the '-classpath' option to specify the class path for the 'java' tool to load any classes required during the execution.

The most commonly used "java" option is "-classpath", which specifies a list of path names where the launcher will search for compiled type definitions. If "-classpath" is not specified, the current directory will be used as the class path.

To experiment how the compiler uses "-classpath", I wrote the following simple source file, Echoer.java:

/**
 * Echoer.java
 * Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
 */
public class Echoer {
   private String req = null;
   private String res = null;
   public void setReq(String r) {
      req = new String(r);
      char[] a = r.toCharArray();
      int n = a.length;
      for (int i=0; i<n/2; i++) {
         char t = a[i];
         a[i] = a[n-1-i];
         a[n-i-1] = t;
      }
      res = new String(a);
   }
   public String getRes() {
      return res;
   }
}

I also wrote the following testing class, EchoerTest.java:

/**
 * EchoerTest.java
 * Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
 */
public class EchoerTest {
   public static void main(String[] a) {
      Echoer e = new Echoer();
      e.setReq("Hello world!");
      System.out.println(e.getRes());
   }
}

Then I stored them in two different directories, and tried to launch EchoerTest:

C:\herong>mkdir echo
C:\herong>copy Echoer.java echo

C:\herong>mkdir test
C:\herong>copy EchoerTest.java test

C:\herong>cd test

C:\herong>javac -classpath ..\echo EchoerTest.java

>java EchoerTest
Exception in thread "main" java.lang.NoClassDefFoundError: Echoer
        at EchoerTest.main(EchoerTest.java:7)

C:\herong>java -classpath ..\echo EchoerTest
Exception in thread "main" java.lang.NoClassDefFoundError: EchoerTest

C:\herong>java -classpath .;..\echo EchoerTest
!dlrow olleH        

Note that:

  • The first time I tried to launch "EchoerTest" without "-classpath", "java" failed to find "Echoer" class, because "java" uses the current directory as the default class path.
  • The second time I tried to launch "EchoerTest" with "-classpath ..\echo", "java" failed to find "EchoerTest" class, because the specified class path didn't include the current directory.
  • The third time I tried to launch "EchoerTest" with "-classpath .;..\echo", "java" was able to find both "EchoerTest" and "Echoer".

Sections in This Chapter

'java' - Java Launching Command and Options

Launching Hello.java - My First Java Program

Option "-classpath" - Specifying Class Path

Option '-jar' - Specifying Executable JAR Files

Option '-X' - Specifying Non-Standard Options

'javaw' - Launching Java Programs without Console

Dr. Herong Yang, updated in 2008
Option "-classpath" - Specifying Class Path