Sub topic 3
Naming packages
This chapter assumes you can write and compile a class with a main method and that you know what a package declaration looks like. It covers how to choose package names that stay unique, how to handle domain names that are not valid identifiers, and how to arrange names inside a project.
What a package name has to do
A package name is the first part of every fully qualified class name. Two jobs depend on it:
- Uniqueness. If two libraries both define a class
Parser, the full names must differ, or the class loader cannot tell them apart. - Orientation. A reader should be able to guess from the name what the classes inside are for.
Java has no central registry of package names. The language relies on a convention that makes collisions unlikely without any coordination.
The reverse domain name convention
Take a domain name that your organization controls, reverse its parts, and use the result as a prefix. Domain names are already unique worldwide, so a prefix built from one is unique too.
| Domain | Package prefix |
|---|---|
| `example.com` | `com.example` |
| `shop.example.com` | `com.example.shop` |
| `apache.org` | `org.apache` |
| `cs.example.edu` | `edu.example.cs` |
Everything after the prefix is yours to organize. A shop application might use com.example.shop, with com.example.shop.model and com.example.shop.payment below it.
If you have no domain, pick a prefix you are unlikely to share with anyone. Many people use a code-hosting name that they own, such as io.github.username. Avoid inventing a com. prefix for a domain you do not control, because your code may eventually meet a library that really does own it.
Formatting rules
The convention for the text of the name is simple.
- Use all lowercase letters. Class names use
UpperCamelCase, so lowercase package segments let you tellcom.example.Productapart at a glance: lowercase segments are packages, and the capitalized one is the class. - Separate segments with dots. Each dot marks one directory level on disk.
- Prefer short, single-word segments such as
model,util, orpayment. Do not use underscores or camel case to join words. Writeinventory, notinventory_serviceorinventoryService. - Use nouns. A package describes a body of related code, not an action.
The compiler enforces only that each segment is a legal Java identifier. Everything else is convention, but nearly every Java codebase follows it, and tools and colleagues expect it.
Domains that are not valid identifiers
Some domain names cannot be used as they are. A hyphen is not legal in an identifier, a segment cannot be a Java keyword, and a segment cannot begin with a digit. The Java Language Specification recommends these fixes:
| Problem | Example domain | Resulting package prefix |
|---|---|---|
| Hyphen in a part | `my-company.com` | `com.my_company` |
| Part is a keyword | `int.example.org` | `org.example.int_` |
| Part starts with a digit | `1password.com` | `com._1password` |
In practice, many teams simply drop the hyphen (com.mycompany). That is fine as long as the whole team does it the same way. Pick one rule and apply it everywhere.
Reserved and special prefixes
Do not use java. or javax. for your own code. The java.* packages belong to the platform, and the class loader refuses to define a class in a package whose name starts with java.. Attempting it fails at run time with a SecurityException ("Prohibited package name"), not at compile time, which makes it an annoying surprise.
The jdk. and sun. prefixes name internal implementation packages. Avoid them too, because they are not stable API.
Seeing a package name at run time
A class can report the package it belongs to. This is useful when you want to confirm that your directory layout and your declaration agree.
package com.example.shop.model;
public class PackageNameDemo {
public static void main(String[] args) {
Class<?> type = PackageNameDemo.class;
System.out.println(type.getPackageName());
System.out.println(type.getName());
}
}Save the file as src/com/example/shop/model/PackageNameDemo.java, then compile and run it. The method getPackageName() exists from Java 9 onward.
javac -d out src/com/example/shop/model/PackageNameDemo.java
java -cp out com.example.shop.model.PackageNameDemoThe output is:
com.example.shop.model
com.example.shop.model.PackageNameDemoThe first line is the package name. The second is the fully qualified class name, which is the package name, a dot, and the simple class name.
Packages are flat, not nested
The dots in a package name look like a tree, and on disk they are one. For the language, though, there is no containment. com.example.shop and com.example.shop.model are two unrelated packages that happen to share a prefix.
This has practical consequences:
- Importing
com.example.shop.*does not import classes fromcom.example.shop.model. Each package must be imported separately. - Package-private members of
com.example.shopare not visible to code incom.example.shop.model, and the reverse is also true. - A "parent" package gets no special access to a "child" package.
The prefix relationship is a naming and organization tool only. If you rely on it for visibility, the compiler will reject the code.
Choosing the structure under your prefix
Once the prefix is fixed, you decide how to divide the code. Two approaches are common.
Package by layer groups classes by technical role:
com.example.shop.modelcom.example.shop.servicecom.example.shop.repository
This is easy to learn, but a change to one feature touches several packages. It also pushes you to make classes public so that other layers can reach them, which weakens encapsulation.
Package by feature groups classes by what they do for the user:
com.example.shop.catalogcom.example.shop.checkoutcom.example.shop.shipping
Related classes sit together, so more of them can stay package-private and hide their details. Larger applications often move in this direction.
Neither is required. What matters is that a new reader can predict where a class lives, and that the scheme is applied consistently. Keep the hierarchy shallow. Three or four levels below the prefix is usually enough, and deeper trees mostly add typing.
Common mistakes
- Mismatch between name and directory. If a file declares
package com.example.shop;but sits insrc/shop/,javacmay compile it, butjavawill not find the class by its full name. Chapter material on directory layout covers this in detail. - Capital letters in package names.
com.Example.Shopcompiles, but it breaks convention and causes trouble on case-insensitive file systems, whereShopandshopcollide. - Reusing a class name as a package name. A package called
com.example.shop.productnext to a class calledProductis legal, but a lowercase name that matches a variable can cause obscuring problems. If a local variable is namedproduct, the expressionproduct.Nameis read as a field access on the variable, not as a package reference. Pick segment names that you are unlikely to use for variables, or use a less generic noun. - Renaming late. Changing a package name changes every
import, every file location, and any configuration that mentions the full name, such as logging setups or serialization data. Settle the prefix early.
Exercise
Your company owns the domain fast-parts.co.uk. Give a valid package prefix following the reverse domain convention and the JLS fix for hyphens, and then say whether code in uk.co.fast_parts.shop can use the package-private members of a class in uk.co.fast_parts.shop.model.
Show answer
The prefix is uk.co.fast_parts, with the parts reversed and the hyphen replaced by an underscore (a team may also agree to drop the hyphen and use uk.co.fastparts). No, it cannot use them. uk.co.fast_parts.shop and uk.co.fast_parts.shop.model are different packages, and package-private access applies only within the same package. The shared prefix gives no special access.
Exercise
A file at src/com/example/shop/model/Product.java starts with package com.example.Shop.model;. What is wrong, and what is the correct declaration?
Show answer
The declaration uses a capital S in Shop, which breaks the all-lowercase convention and does not match the directory name shop. The correct declaration is package com.example.shop.model;.