Unit 11: Archiving Java code

Before you begin

This unit is part of the “Intro to Java programming” learning path. Although the concepts discussed in the individual units are standalone in nature, the hands-on component builds as you progress through the units, and I recommend that you review the prerequisites, setup, and unit details before proceeding.

Unit objectives

  • Know how to create a JAR file in Eclipse
  • Be able to import third-party code into your Java applications

Creating JARs

Now that you’ve learned a bit about writing Java applications, you might be wondering how to package them up so that other developers can use them, or how to import other developers’ code into your applications. This unit shows you how.

The JDK ships with a tool called JAR, which stands for Java Archive. You use this tool to create JAR files. After you package your code into a JAR file, other developers can drop the JAR file into their projects and configure their projects to use your code.

Creating a JAR file in Eclipse is easy. Watch as I take you through the steps.

Using third-party applications

The JDK is comprehensive, but it doesn’t do everything you need for writing great Java code. As you grow more comfortable with writing Java applications, you might want to use more and more third-party applications to support your code. The Java open source community provides many libraries to help shore up these gaps.

Suppose, for example, that you want to use Apache Commons Lang, a JDK replacement library for manipulating the core Java classes. The classes provided by Commons Lang help you manipulate arrays, create random numbers, and perform string manipulation.

Let’s assume you’ve already downloaded Commons Lang, which is stored in a JAR file. To use the classes, your first step is to create a lib directory in your project and drop the JAR file into it:

  1. Right-click the Intro root folder in the Eclipse Project Explorer view.
  2. Click New > Folder and call the folder lib.
  3. Click Finish.

The new folder shows up at the same level as src. Now copy the Commons Lang JAR file into your new lib directory. For this example, the file is called commons-lang3-3.4.jar. (It’s common in naming a JAR file to include the version number, in this case 3.4.)

Now all you need to do is tell Eclipse to include the classes in the commons-lang3-3.4.jar file into your project:

  1. In Package Explorer, select the lib folder, right-click, and select Refresh.
  2. Verify that the JAR shows up in the lib folder: Screenshot of the refreshed lib folder
  3. Right-click commons-lang3-3.4 and choose Build Path > Add to Build Path.

After Eclipse processes the code (that is, the class files) in the JAR file, they’re available to reference (import) from your Java code. Notice in Project Explorer that you have a new folder called Referenced Libraries that contains the commons-lang3-3.4.jar file.

Previous: Java CollectionsNext: Writing good Java code

J Steven Perry