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

'java' - The Java Launcher

Part:   1  2   3  4 

Java Tool Tutorials

© 2006 Dr. Herong Yang

Latest updates:

  'javac' - The Java Compiler

  'java' - The Java Launcher

  'jdb' - The Java Debugger

  JAR File & 'jar' Tool

  Certificates and 'keytool'

  Installing J2SE 1.5.0

... Table of Contents

(Continued from previous part...)

"-classpath" - Specifying Class Path

"-classpath" is an option to specify 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:

>mkdir echo
>copy Echoer.java echo

>mkdir test
>copy EchoerTest.java test

>cd test

>javac -classpath ..\echo EchoerTest.java

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

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

>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".

(Continued on next part...)

Part:   1  2   3  4 

Dr. Herong Yang, updated in 2006
Java Tool Tutorials - Herong's Tutorial Notes - 'java' - The Java Launcher