Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 07 / Topic 1 of 7

Why packages

A package is a named group of classes, the Java equivalent of a folder of related files. Without packages, every class in a program would need a globally unique name — two libraries both shipping a class called Util would collide the moment you used both. Think of a block of flats in Pune: two buildings can both have a "Flat 101", because the building name (the package) tells you which one you mean.

A class states its package with a package declaration, the first non-comment line of the file:

package billing;

public class Invoice {
    // ...
}

A class with no package line sits in the default (unnamed) package. That is fine for a one-file toy program, like Hello.java in Part 1, but real programs always use named packages — the default package cannot be import-ed from a named package, and every serious tool (IDEs, build tools, the module system in later Java versions) assumes named packages.

To use a class from another package, import it by its fully qualified name (package + class name):

import billing.Invoice;
import billing.util.Formatter;

A dotted package name (billing.util) is not special syntax — it is just a package named util that lives inside the folder for package billing, the same way billing.util.Formatter is a class named Formatter inside that package. Chapter 2 shows exactly where that class must live on disk.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide