How to Use a Package Statement in Java

The package statement identifies the package that a Java program belongs to. If your program does not include a package statement, the program belongs to the default package, which is simply a package that has no name.

This is acceptable for short programs written for testing purposes. But if you plan to distribute your program, you should create a package for the program and use a package statement in all of the program’s source files to identify the package.

The syntax of the package statement is simple:

package package-name;

Package-name refers to the name of the package that the program should be added to. You can use any name you wish, but it's best to follow the established convention of transposing your Internet domain name (if you have one). (Transposing your domain name ensures that your package names are unique.)

Notice that package names are in lowercase letters. That’s not an absolute requirement, but it’s a Java convention that you ought to stick to.

You can add additional levels beyond the domain name if you want. For example, you can put your utility classes in a package named com.lowewriter.util. Any class that you want to include in this package must include the following statement:

package com.lowewriter.util;

After you decide on a package name, you can create a folder structure to hold the classes for the package. This structure should start with a folder you will use as the root for all of your Java classes. You should create a directory, such as c:\javaclasses.

Then, within the class root folder, create folders and subfolders that correspond to the parts of your package name. For example, for a package named com.lowewriter.util, create a folder named com, then within that folder create another folder named lowewriter. Finally, in the lowewriter folder, create a folder named util.