The Plain Picture#
A library with thousands of books doesn't put them on one shelf. It has sections — Science, History — and within them sub-sections. Two books can have the same title if they're in different sections.
The Real Names#
A package is a named group of related classes, matching a folder on disk. Names are usually a reversed web domain:
com.studybuddy.quiz.The fully qualified name of a class includes its package:
java.util.ArrayList,com.studybuddy.quiz.Quiz.importlets you use a class by its short name.import java.util.*;imports every class injava.util.java.langis imported automatically — that's whyString,Math,IntegerandSystemneed no import.
Under the Hood#
src/main/java/
└── com/studybuddy/
├── model/
│ ├── Student.java package com.studybuddy.model;
│ └── Note.java
└── quiz/
└── QuizService.java package com.studybuddy.quiz;
import com.studybuddy.model.Student;Each
.javafile starts with itspackageline, thenimportlines, then the class.A file can hold only one
publictop-level class, named like the file.Classes in the same package can see each other's non-private members (Object-Oriented Programming explains access levels).
Real projects are built with a build tool — Maven or Gradle — which compiles everything, downloads libraries (dependencies) and runs tests.
src/main/java/is the standard folder layout they expect. You'll see the Python equivalents in Python Packaging and Tools (coming soon).
For DSA practice you won't need packages at all: LeetCode gives you one class, and single-file programs run with java Main.java.
Check yourself
3 questionsWhat is a package, and what does it correspond to on disk?
Show answerHide answer
A named group of related classes; a folder (matching the package name).
Why doesn't String need an import?
Show answerHide answer
It's in java.lang, which is imported automatically.
How many public top-level classes can one file contain?
Show answerHide answer
One, and the file must be named after it.