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) 2015, HerongYang.com, All Rights Reserved.
 */
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) 2015, HerongYang.com, All Rights Reserved.
 */
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\test>javac -classpath ..\echo EchoerTest.java

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

C:\herong\test>java -classpath ..\echo EchoerTest
Error: Could not find or load main class EchoerTest

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

Note that:

Last update: 2015.

Table of Contents

 About This Book

 Java Tools Terminology

 Installing Java 8 on Windows

 'javac' - The Java Program Compiler

'java' - The Java Program Launcher

 '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

 'jdb' - The Java Debugger

 'jconsole' - Java Monitoring and Management Console

 'jstat' - JVM Statistics Monitoring Tool

 JVM Troubleshooting Tools

 jvisualvm (Java VisualVM) - JVM Visual Tool

 'jar' - The JAR File Tool

 'javap' - The Java Class File Disassembler

 'keytool' - Public Key Certificate Tool

 'native2ascii' - Native-to-ASCII Encoding Converter

 Outdated Tutorials

 References

 PDF Printing Version