Why do we need packages?
12 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A package is a named group of related classes, like a folder that holds related files. Java keeps its own classes in packages too, such as java.lang and java.util.
Classes need a home
A college app has classes for students, fees, exams and the library, and two teams both want a class named Report. A package is a named group of related classes, kept in its own folder, such as com.college.students.
college.com gives com.college.The full name of a class
Since Reading input with Scanner (opens in a new tab) you have written import java.util.Scanner;. The full name (fully qualified name) of a class is its package name, a dot and the class name: java.util.Scanner is the class Scanner in the package java.util.
Example · Using classes by their full name
public class FullName { public static void main(String[] args) { int[] marks = {72, 95, 60}; java.util.Arrays.sort(marks); System.out.println(java.util.Arrays.toString(marks)); System.out.println(java.lang.Math.max(72, 95)); }}[60, 72, 95] 95
What this code does
java.util.Arraysis the full name ofArrays(opens in a new tab). With the full name, noimportline is needed.java.lang.Math.maxis the same method asMath.max. You may skipjava.lang.because Java adds that package for you.
Full names are also how Java tells the two Report classes in the picture apart: com.college.students.Report and com.college.fees.Report. Typing full names everywhere is long; the import line is the shortcut, covered in Use classes from other packages with import (opens in a new tab).
Java's own packages
Math works with no import line, but Scanner does not. Java adds the package java.lang to every program for you; every other package, such as java.util, has to be named.
Classify
java.lang or java.util?
Tap a class, then tap the package it lives in.
Next step
Check your understanding
8 quick questions