Packages in Java

Naveen AnamaneniUpdated · 5 min read

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:

PackageContainsImport needed?
java.langString, Math, System, Integer, ObjectNo, imported automatically
java.utilArrayList, HashMap, Scanner, RandomYes
java.io and java.nio.fileFiles and streamsYes
java.timeLocalDate, DurationYes
java.mathBigDecimal, BigIntegerYes
java.sqlDatabase 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.

Each dot in a package name is a folder

The first line of each file names its package, and the file sits in the matching folder:

src/com/poolstring/bank/service/TransferService.java
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());
    }
}
src/com/poolstring/bank/app/BankApp.java
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):

Terminal
javac -d out $(find src -name "*.java")
java -cp out com.poolstring.bank.app.BankApp
Terminal output
[audit] Navika: withdraw 2000
[audit] Advitha: deposit 2000
Moved 2000 to Advitha
Transfer refused for Advitha
Navika: 3000
Advitha: 3000

How it works

  1. javac -d out compiles every source file and writes each .class file into a folder tree under out that mirrors the package: out/com/poolstring/bank/app/BankApp.class, and so on. ($(find ...) lists all the .java files on macOS and Linux; on Windows, list them or use a build tool.)
  2. java -cp out tells the JVM to look for classes under out.
  3. 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

  1. Easy: Write the fully qualified names of Scanner, LocalDate, BigDecimal and TransferService.
  2. Harder: Create the bank project on your machine with the three packages above, compile it with javac -d out, and run it. Then look inside out and describe the folder tree.

Quick check: Packages

4 questions
1Which package is available without an import?
2Where must the package statement go?
3How do you run BankApp in package com.poolstring.bank.app from compiled classes in out?
4What does javac -d out do with packages?

Key Takeaways

Was this tutorial helpful?

Lesson 145 of 482