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:

    What, then, is the basic difference between today’s computer and an intelligent being? It is that the computer can be made to see but not to perceive. What matters here is not that the computer is without consciousness but that thus far it is incapable of the spontaneous grasp of pattern—a capacity essential to perception and intelligence.
    Rudolf Arnheim (b. 1904)

    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)