Creating and Using Java Packages and Jar Files
 
Part A. Packages
- A package is a collection of related classes.
- A class path is a list of folders in which the Java compiler
and interpreter look to find imported classes.
- To create and test a package named StackClass, follow these directions:
- Reread the document Running Java from the DOS Prompt.
- Make sure that the path to the Java compiler and interpreter is set up
correctly.
- Create the new folder c:\mypackages\stackqueue.
- Download the source code files
Stack.java and
Queue.java into c:\mypackages\stackqueue.
Notice that the files Stack.java and Queue.java have as their first line
package stackqueue;
- Compile the downloaded source code files from Step 2 to create
Stack.class and Queue.class in c:\mypackages\stackqueue. You can use BlueJ, TextPad,
or compile directly from the DOS prompt.
- Create the folder c:\testfolder.
- Download the source code file
TestStackQueue.java into c:\testfolder.
Notice that Main.java has as its first line
import stackclass;
- Compile TestStackQueue.java with:
javac -classpath c:\mypackages Main.java
This creates TestStackQueue.class.
- Run TestStackQueue.class with:
java -classpath c:\mypackages Main
- Alternatively, you can set the classpath environment variable with
set classpath=.;c:\mypackages
- Then you can compile and run TestStackQueue with these lines:
javac TestStackQueue.java
java TestStackQueue
 
Part B. Jar Files
- A Jar file is compressed file, similar to a zip file,
containing the .class files of a package.
- To import a Jar file instead of the uncompressed .class files, following
these directions:
- Open a Command Prompt window (Start, All Programs, Accessories, Command Prompt).
- Change to the folder c:\mypackages using the DOS cd command.
- Create a Jar file with the following line:
jar cf stackqueue.jar stackqueue\*.class
- Move the file Stackqueue.jar to the folder
c:\jdk1.3\jre\lib\ext.
This assumes that jdk1.3 is the folder in which the Sun Java software has been
installed.
- Change to the folder c:\testfolder.
- Compile and run TestStackQueue with these lines:
javac TestStackQueue.java
java TestStackQueue
Note that no classpath directive or environment variable is needed to access
Jar files placed in c:\jdk1.3\jre\lib\ext.