Packages

A package is a namespace — a folder-like structure that groups related classes together and keeps names from colliding. Without packages, two different libraries that both define a class named List would conflict. With packages, they can coexist as java.util.List and com.example.List.

Declaring a Package

A file declares which package it belongs to with a package statement as the very first line of code (only comments may come before it). The package name must match the folder structure the file lives in.

package com.example.myapp;

public class Main {
  public static void main(String[] args) {
    System.out.println("Running from com.example.myapp");
  }
}
          
Note: A file declaring package com.example.myapp; must sit inside a folder path of com/example/myapp/ relative to your source root. The compiler and IDE both rely on this match.

Importing Classes from Other Packages

To use a class that lives in a different package, bring it into scope with an import statement at the top of the file, after the package line (if any).

Example: Importing from java.util

package com.example.myapp;

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> names = new ArrayList<>();
    names.add("Sonu");
    System.out.println(names);
  }
}

What's happening:

  • import java.util.List; and import java.util.ArrayList; let this file refer to List and ArrayList by their short names instead of the full java.util.List.
  • Without the import, you'd have to write the fully-qualified name every time: java.util.List<String> names = ...

java.lang — Auto-Imported for You

One package is special: java.lang. It's automatically imported into every Java file without needing an explicit import statement. It contains the fundamental classes you've already been using throughout this track, like String, System, Object, Math, and the exception classes.

Tip: This is why System.out.println(...) and String have worked in every example so far without any import line at the top — they both live in java.lang.

Other Commonly-Used Built-in Packages

The Java standard library ships with many packages beyond java.lang. Two you'll run into constantly:

PackageUsed for
java.utilCollections like List, Map, and Set, plus utilities like Scanner and Random
java.ioReading and writing files and streams

We'll dive into both of these in detail in the Collections Framework and File I/O lessons later in this track.

Next up: learn how public, private, and friends control visibility across packages in Access Modifiers.