Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 201 ยท Object-Oriented Programming

Packages and Imports

Learn Java packages and imports - package names and folders, single-type and on-demand imports, name clashes, static import, import module (Java 25) and the classpath.

A real Java application has hundreds or thousands of classes, and the JDK alone has several thousand. Without some organization, names would collide constantly: there's a List in java.util and another in java.awt, a Date in java.util and another in java.sql. Packages solve this. A package is a named group of related classes, like a folder, and it gives every class a unique full name such as java.util.List.

Imports are the other half. They let you write the short name List in your code instead of java.util.List every time. This lesson covers how packages are named and laid out on disk, every kind of import (single-type, on-demand, static, and the new module import of Java 25), how Java resolves name clashes, how packages relate to access control, and how the compiler and JVM find your classes through the classpath.

What a package is

Every class belongs to exactly one package. The package does three jobs:

  1. Namespace. The class's full name, its fully qualified name, is the package name plus the class name: java.util.ArrayList, java.time.LocalDate, com.example.shop.Cart. Two classes may share a simple name if they're in different packages.
  2. Organization. Related classes live together: java.time holds date and time classes, java.nio.file holds file system classes. In your code, com.example.shop.billing might hold invoices and payments.
  3. Access boundary. Members with no access modifier are package-private: visible to every class in the same package and hidden from all others (Access Modifiers).

You can always use a class by its fully qualified name, without any import:

Java Fully qualified names need no import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

That works, but it's noisy. Imports exist so you don't have to write it.

Declaring a package

To put a class in a package, start the file with a package declaration. It must be the first statement in the file (only comments may come before it):

Java
package com.example.shop;

public class Cart {
    // ...
}

The fully qualified name of this class is now com.example.shop.Cart.

Naming conventions

  • All lowercase, with dots between parts: com.example.shop.billing. Never Shop or shop_billing.
  • Start with a reversed domain name you control: a company owning example.com uses com.example. That makes names globally unique, so your com.example.util.Strings never collides with someone else's library. Open-source projects often use their project domain (org.apache.commons, io.github.username).
  • Then group by feature or layer: com.example.shop.cart, com.example.shop.payment. Many teams prefer package by feature (everything about carts together) over package by layer (all controllers in one package, all repositories in another), because features change together.
  • The names java and javax are reserved for the platform. You can't declare package java.mine;.

Packages are folders

The package structure must match the folder structure of your source files. A class in com.example.shop lives in com/example/shop/ under your source root. A typical project (laid out by Maven or Gradle) looks like this:

TEXT
my-shop/
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main/java/
    โ”‚   โ””โ”€โ”€ com/example/shop/
    โ”‚       โ”œโ”€โ”€ App.java              package com.example.shop;
    โ”‚       โ”œโ”€โ”€ cart/
    โ”‚       โ”‚   โ”œโ”€โ”€ Cart.java         package com.example.shop.cart;
    โ”‚       โ”‚   โ””โ”€โ”€ CartItem.java
    โ”‚       โ””โ”€โ”€ payment/
    โ”‚           โ””โ”€โ”€ Payment.java      package com.example.shop.payment;
    โ””โ”€โ”€ test/java/
        โ””โ”€โ”€ com/example/shop/cart/
            โ””โ”€โ”€ CartTest.java         same package as Cart, different folder tree

Tests usually live in the same package as the code they test, in a parallel folder tree. That lets them use package-private members.

The examples on this site are single files without a package line: their classes are in the unnamed package. That's fine for small programs and experiments. Real projects always use named packages, partly because classes in the unnamed package can't be imported by classes in named packages. (The Java source launcher, which runs our examples, also insists that a file with a package line sit in matching folders, which is why the package examples here are read-only.)

Subpackages aren't special

Despite the dots, com.example.shop and com.example.shop.cart are two unrelated packages as far as Java is concerned. Package-private members of one are invisible to the other, and importing one doesn't import the other. The hierarchy is only a naming and folder convention.

Single-type imports

An import declaration goes after the package line and before the first class. The most common form names one type:

Java
package com.example.shop.cart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.example.shop.payment.Payment;

public class Cart {
    private final List<CartItem> items = new ArrayList<>();   // CartItem: same package, no import
    // ...
}

Classes in the same package never need an import. Neither do classes in java.lang, which every file imports automatically: that's why String, Math, Integer, System, Thread and IO work everywhere with no import.

Some facts about imports that surprise people:

  • Imports don't load or include anything. They're a compile-time shorthand that tells the compiler what a simple name means. The compiled class file contains fully qualified names; an unused import costs nothing at run time (but IDEs flag it as clutter).
  • Imports don't cascade. If class A imports java.util.List, a class B that uses A still needs its own import to write List.
  • You import types, not packages. import java.util; is an error. You import a type (java.util.List), all types of a package (java.util.*), or static members.

On-demand imports and name clashes

A type-import-on-demand (wildcard) declaration makes every public type of a package available by its simple name:

Java
import java.util.*;      // List, Map, ArrayList, HashMap, Optional, ...

The wildcard covers one package only, not subpackages: java.util.* doesn't bring in java.util.function.Function or java.util.concurrent.ExecutorService.

Wildcards are convenient, but they make it harder to see where a class comes from, and they can create ambiguity. Both java.util and java.awt have a public type called List. This program fails to compile on purpose:

Java Two wildcards, one ambiguous name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports reference to List is ambiguous, followed by both class java.awt.List in java.awt and interface java.util.List in java.util match. Note that the error only appears because the code uses List. Unused clashes are fine.

The fix is a single-type import, which always wins over on-demand imports. Add import java.util.List; below the wildcards and the program compiles and prints []. If you need both types in one file, import one and use the fully qualified name for the other:

Java Using two classes with the same simple name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

(Both of these Date classes are legacy. New code uses java.time types like Instant and LocalDate; see Dates and Times.)

The rules of precedence

When the compiler sees a simple type name, it looks in this order, and the first match wins:

  1. Types declared in the current file (including nested types in scope).
  2. Single-type imports.
  3. Other types in the same package.
  4. On-demand imports (java.util.*) and java.lang, all at the same level, so two of them can clash.
  5. Module imports (import module ..., below), which come last.

Most style guides (and IDE defaults) prefer explicit single-type imports for this reason: every name's origin is visible at the top of the file, and adding a class to some library later can never make your code ambiguous. IDEs maintain the import list for you, so the extra lines cost nothing.

Static imports

A normal import brings in types. A static import brings in static members (fields and methods) of a type, so you can use them without the class name:

Java Static imports for methods and constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Members declared in your class take precedence over statically imported ones with the same name. Fields and methods are looked up separately, though: the field max is used where a variable is expected, but the class declares no method named max, so the call max(2, 7) still finds Math.max. Mixing names like that is legal but confusing, which brings us to the guideline.

Use static imports sparingly, where the origin is obvious and the code becomes clearly more readable:

  • math-heavy code (sqrt, PI, abs);
  • test assertions (import static org.junit.jupiter.api.Assertions.assertEquals;, see Unit Testing with JUnit);
  • stream collectors and comparators (toList, groupingBy, comparing);
  • constants from an enum or a constants class used many times.

Avoid import static wildcards on classes whose members have generic names (of, valueOf, get): the reader can't tell which class's of is called.

Module imports (Java 25)

Java 25 adds a third kind of import. A module import declaration imports every public type in every package that a module exports:

Java
import module java.base;      // java.util, java.io, java.nio.file, java.time, java.util.function, ...

java.base is the core module of the JDK, so one line gives you List, Map, Path, Files, LocalDate, Function and hundreds more. Other modules work the same way: import module java.sql; brings in java.sql and javax.sql, import module java.net.http; the HTTP client. Importing a module also imports the modules it declares requires transitive, so import module java.sql; covers the parts of java.xml that the SQL API exposes. Modules themselves are covered in The Java Module System.

You've been using this feature already: compact source files (void main() { ... } with no class) implicitly start with import module java.base;. That's why examples like the for loop lesson's can use List and Arrays with no import at all.

Because module imports pull in so many names, clashes are more likely. Module imports have the lowest precedence, so any single-type or on-demand import shadows them:

Java Resolving a clash between module imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Remove the line import java.sql.Date; and the compiler says reference to Date is ambiguous (both java.sql.Date in java.sql and java.util.Date in java.util match).

When should you use module imports? They're great for scripts, prototypes, teaching and JShell-style exploration. In large production code bases, most teams still prefer explicit single-type imports, because they document exactly which classes a file depends on.

The classpath: how Java finds classes

The compiler and the JVM turn fully qualified names into files using the folder convention. To find com.example.shop.cart.Cart, the JVM looks for com/example/shop/cart/Cart.class in each location on the classpath: a list of folders and JAR files.

Terminal
# Compile all sources into the out/ folder (folders mirror the packages)
javac -d out src/main/java/com/example/shop/App.java src/main/java/com/example/shop/cart/*.java

# Run: put out/ on the classpath and name the main class by its full name
java -cp out com.example.shop.App

# Add libraries: separate entries with ; on Windows and : on macOS/Linux
java -cp "out:lib/jackson-databind.jar:lib/jackson-core.jar" com.example.shop.App

# Java 22+: launch straight from source; other classes are found in the source tree
java src/main/java/com/example/shop/App.java

If a class isn't on the classpath, you'll see ClassNotFoundException or NoClassDefFoundError at run time, or package com.example.shop.cart does not exist at compile time. In practice, build tools like Maven and Gradle assemble the classpath for you from your declared dependencies, and IDEs do the same. Knowing the underlying rule still helps when something goes wrong: the package name, the folder path and the classpath entry must line up exactly.

package-info.java

A package can have one special file, package-info.java, holding documentation and annotations for the package as a whole:

Java
/**
 * Shopping cart: adding items, computing totals and applying discounts.
 */
package com.example.shop.cart;

Javadoc uses it for the package summary page, and some frameworks read package-level annotations from it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file has import java.util.*;. Which type can it use by its simple name without another import?

    An on-demand import covers only the types directly in that package. Subpackages like java.util.function and java.util.concurrent are separate packages that need their own imports.
  2. 2. A file has import java.util.*;, import java.awt.*; and import java.util.List;, then declares List<String> x;. What happens?

    A single-type import shadows on-demand imports, so the ambiguity between the two wildcards is resolved in favor of java.util.List.
  3. 3. Which statement about imports is true?

    Imports are a compile-time shorthand. Class files use fully qualified names, classes in the same package (and java.lang) need no import, and subpackages are unrelated packages.
  4. 4. Why can a compact source file (void main() { ... }) use List and Files without any import?

    Java 25 compact source files start with an implicit import module java.base, which makes every public type in every package exported by java.base available.
  5. 5. Where must the source file of the class com.example.app.Main be placed?

    Each part of the package name is a folder. The compiler, the source launcher and the class loader all rely on the path matching the package.

Summary

  • A package is a namespace, a folder and an access boundary; a class's fully qualified name is its package plus its simple name.
  • package com.example.shop; must come first in the file, the folders must match, and names are lowercase reversed domains.
  • Subpackages are unrelated packages; same-package classes and java.lang need no import.
  • import a.b.Type; imports one type, import a.b.*; all types of one package (not subpackages); single-type imports win over wildcards, and clashing wildcards cause reference to ... is ambiguous only when the name is used.
  • import static brings in static members; use it sparingly for obvious names like sqrt or test assertions.
  • import module java.base; (Java 25) imports everything a module exports; it has the lowest precedence, and compact source files include it automatically.
  • The classpath tells the compiler and JVM where to find com/example/.../Type.class; build tools manage it for you.

Next: Exceptions and try-catch, where you'll learn what happens when things go wrong at run time and how to handle it.