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 test of freedom is perhaps less in what we are free to do than in what we are free not to do. It is the freedom to refrain, withdraw and abstain which makes a totalitarian regime impossible.
    Eric Hoffer (1902–1983)

    Girls who put out are tramps. Girls who don’t are ladies. This is, however, a rather archaic usage of the word. Should one of you boys happen upon a girl who doesn’t put out, do not jump to the conclusion that you have found a lady. What you have probably found is a lesbian.
    Fran Lebowitz (b. 1951)