A short note on packages
Khalid A. Mughal


A package statement can only occur as the first statement in a Java source file.
The statement

package com.acme;

instructs the compiler to place the Java byte code for all the classes (and interface) specified in the source file in the package com.acme.

Think of a package name as a path in the file system.
In this case the package name com.acme corresponds to the path name com/acme.
So the Java byte code for all the classes (and interface) specified in the source file Temperature.java will be placed under the catalog com/acme.

Question: where is com/acme?

You can choose the location of com/acme by using the -d option (d for destination) when compiling with javac.
Assume that the current directory is called work, and the source code file Temperature.java is to be found here.
The command

javac -d . Temperature.java

(note the dot after the -d option to indicate the current directory)
will create com/acme under the current directory, and place the Java byte code for all the classes (and interface) in it.


                                  work
                                   |
                        ------------------------
                        |                      |
                  Temperature.java            com
                                               |
                                              acme
                                               |
                 ----------------------------------------------------------
                 |                             |                          |
           Temperature.class         TemperatureConverter.class      IFtoC.class

How do we run the program?

Since the current directory is work and we want to run Temperature.class, the *full name* of the Temperature class must be specified in the java command:

java com.acme.Temperature 

This will now result in the main() method from the com.acme.Temperature class being executed.

Read more about packages in the handout on OBP