Packages in Java
A big library doesn't pile all its books on one table. It has sections, shelves and labels, so two books with the same title can sit in different sections without confusion. A package is a section for Java classes: a named group of related classes and interfaces. Packages keep large projects organized, prevent name clashes (two classes called Date can live in different packages), and work with access modifiers to hide what isn't meant to be used outside.
Built-In Packages
The JDK itself is organized into packages. You've already used several:
| Package | Contains | Import needed? |
|---|---|---|
java.lang | String, Math, System, Integer, Object | No, imported automatically |
java.util | ArrayList, HashMap, Scanner, Random | Yes |
java.io and java.nio.file | Files and streams | Yes |
java.time | LocalDate, Duration | Yes |
java.math | BigDecimal, BigInteger | Yes |
java.sql | Database access (JDBC) | Yes |
A class's fully qualified name is its package plus its simple name: java.util.ArrayList. That full name is what makes it unique.
Writing Your Own Packages
The bank project for this chapter splits its code into three packages: the data model, the business logic and the app that starts everything.
The first line of each file names its package, and the file sits in the matching folder:
package com.poolstring.bank.service;
import com.poolstring.bank.model.Account;
public class TransferService {
public void transfer(Account from, Account to, long amount) {
if (!from.withdraw(amount)) {
System.out.println("Transfer refused for " + from.getHolder());
return;
}
to.deposit(amount);
System.out.println("Moved " + amount + " to " + to.getHolder());
}
}package com.poolstring.bank.app;
import com.poolstring.bank.model.Account;
import com.poolstring.bank.service.TransferService;
public class BankApp {
public static void main(String[] args) {
Account navika = new Account("Navika", 5000);
Account advitha = new Account("Advitha", 1000);
TransferService service = new TransferService();
service.transfer(navika, advitha, 2000);
service.transfer(advitha, navika, 9000);
System.out.println("Navika: " + navika.getBalance());
System.out.println("Advitha: " + advitha.getBalance());
}
}Account.java is shown in full in "Access Modifiers in Java".
Compiling and Running
From the project folder (the one containing src):
javac -d out $(find src -name "*.java")
java -cp out com.poolstring.bank.app.BankApp[audit] Navika: withdraw 2000
[audit] Advitha: deposit 2000
Moved 2000 to Advitha
Transfer refused for Advitha
Navika: 3000
Advitha: 3000How it works
javac -d outcompiles every source file and writes each.classfile into a folder tree underoutthat mirrors the package:out/com/poolstring/bank/app/BankApp.class, and so on. ($(find ...)lists all the.javafiles on macOS and Linux; on Windows, list them or use a build tool.)java -cp outtells the JVM to look for classes underout.- You run the class by its fully qualified name, written with dots.
Classes Without a Package
Every example so far in this course had no package line. Such classes are in the unnamed (default) package. It's fine for small programs and single-file examples, but a class in the default package can't be imported by classes in named packages, so real projects always use packages.
Common Mistakes
Running with the simple name. java -cp out BankApp fails with Could not find or load main class BankApp; use the full name com.poolstring.bank.app.BankApp. (The launcher also happens to accept slashes, com/poolstring/bank/app/BankApp, but dots are the standard form.)
A package line that doesn't match the folder. Tools and the classpath expect them to match (see "Package Naming and Folder Structure").
Putting anything before the package line. Only comments may come before it.
Interview Corner
What is a package in Java and why use it?
A package is a namespace that groups related classes and interfaces, declared with package name; as the first statement of a source file. Packages organize large code bases, prevent naming conflicts through fully qualified names, control access through package-private and protected visibility, and map to a matching folder structure on disk.
Which package is imported by default?
java.lang, which contains String, Object, Math, System and the wrapper classes. Classes in the same package as the current class are also visible without an import.
Practice
- Easy: Write the fully qualified names of
Scanner,LocalDate,BigDecimalandTransferService. - Harder: Create the bank project on your machine with the three packages above, compile it with
javac -d out, and run it. Then look insideoutand describe the folder tree.
Key Takeaways
Was this tutorial helpful?