Skip to lesson
MentorNxt home

Java Programming

Packages, Imports & Access Control

Why do we need packages?

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.

A college app in folders: src, com/college, then students (Report.java, MarksUtil.java) and fees (Report.java, FeeCalculator.java). The folder students is the package com.college.students and fees is com.college.fees. Both packages have a Report class, and they do not clash.
Package names are lowercase words joined by dots, and each word is one folder. Many teams start with their website name backwards: 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

FullName.javaJava
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));    }}
Output
[60, 72, 95]
95

What this code does

  • java.util.Arrays is the full name of Arrays (opens in a new tab). With the full name, no import line is needed.
  • java.lang.Math.max is the same method as Math.max. You may skip java.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.

Packages also decide who may use a class or method: see Access modifiers (opens in a new tab).

Next step

Check your understanding

8 quick questions