Lesson 32 +10 XP

Java Packages and API

Java Packages and API

A package is a group of related classes. Packages keep code organized and avoid name conflicts. The Java API is a huge library of ready-made packages and classes.

Built-in packages

The Java API is divided into packages like:

PackagePurpose
java.utilLists, maps, and other utilities
java.timeDates and times
java.ioReading and writing files
java.netNetworking

Importing a class

Use import to use a class from another package:

import java.util.Scanner;

Scanner myObj = new Scanner(System.in);

Import a whole package

import java.util.*;

The asterisk imports every class in the package.

Classes in the same package

Classes that live in the same package do not need an import.

The java.lang package

java.lang (like String and System) is imported automatically. You never need to write an import for it.

User-defined packages

You can group your own classes into packages using the package statement at the top of the file:

package mypackage;

TL;DR

  • Packages group related classes.
  • The Java API provides many ready-made packages.
  • import brings classes from other packages into scope.
  • java.lang is always available automatically.