Classpath (Java) - Setting The Path To Execute Java Programs - Basic Usage

Basic Usage

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this:

Microsoft Windows Linux
D:\myprogram\ | ---> org\ | ---> mypackage\ | ---> HelloWorld.class ---> SupportClass.class ---> UtilClass.class /home/user/myprogram/ | ---> org/ | ---> mypackage/ | ---> HelloWorld.class ---> SupportClass.class ---> UtilClass.class

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we use the following command:

Microsoft Windows Linux
java -classpath D:\myprogram org.mypackage.HelloWorld java -classpath /home/user/myprogram org.mypackage.HelloWorld

where:

  • -classpath D:\myprogram sets the path to the packages used in the program (on Linux, -classpath /home/user/myprogram)
  • org.mypackage.HelloWorld is the name of the main class

Note that if we ran Java in D:\myprogram\ (on Linux, /home/user/myprogram/) then we would not need to specify the classpath since Java implicitly looks in the current working directory for files containing classes.

Read more about this topic:  Classpath (Java), Setting The Path To Execute Java Programs

Famous quotes containing the words basic and/or usage:

    The basic difference between classical music and jazz is that in the former the music is always greater than its performance—Beethoven’s Violin Concerto, for instance, is always greater than its performance—whereas the way jazz is performed is always more important than what is being performed.
    André Previn (b. 1929)

    Pythagoras, Locke, Socrates—but pages
    Might be filled up, as vainly as before,
    With the sad usage of all sorts of sages,
    Who in his life-time, each was deemed a bore!
    The loftiest minds outrun their tardy ages.
    George Gordon Noel Byron (1788–1824)