Packages and imports

Core Java · lesson 9 of 42 · 3 min read

Organise classes into packages and bring other packages into scope.

Open this lesson in the learning hub

Key points

  • A package is a namespace and a folder path. package com.acme.orders; must be the first line of the file.
  • The folder structure has to match the package name, or the class will not be found.
  • Use a reversed domain name such as com.yourcompany.orders so your class names never clash with a library.
  • import is only shorthand. You can always write the fully qualified name instead.
  • Everything in java.lang (String, Math, Integer, Exception) is imported for you.
  • import static java.lang.Math.max; pulls in a single static member. Use it sparingly — it hides where a name came from.

Example

import java.util.List;

import static java.lang.Math.PI;
import static java.lang.Math.max;

public class Main {
    public static void main(String[] args) {
        List<String> langs = List.of("Java", "Kotlin", "Scala");
        System.out.println("java.util.List needed an import: " + langs);

        System.out.println("java.lang needs no import: " + Integer.toHexString(255) + " " + Math.abs(-5));

        System.out.println("static import: max(3, 9) = " + max(3, 9) + ", PI = " + String.format("%.3f", PI));

        java.time.LocalDate today = java.time.LocalDate.of(2024, 5, 17);
        System.out.println("fully qualified, no import: " + today);
    }
}

A package is a folder plus a namespace; imports just save typing.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.