Nearby lessons

44 of 125

Java - Packages

📌 What You Will Learn
  • What a package is and why we need it
  • How to create and use a package
  • import statements — single and wildcard
  • Access modifiers: public, protected, default, private
  • The classpath and the jar tool

Packages is a core concept of the Java language. This lesson explains What is a Package?, Why Do We Need Packages? and Creating a Package with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is a Package?

A package is a folder (directory) that groups related classes and interfaces together. Just like you keep your study notes subject-wise in different folders, Java keeps related code in different packages.

For example, Java itself is organised into packages:

Example01
Loading editor…

Why Do We Need Packages?

  • Avoid name clashes — two classes with the same name can live in different packages (like two Rahul's in two different classes).
  • Organise code — related classes stay together, like chapters in a book.
  • Access protection — packages control who can see the classes (using access modifiers).
  • Easy distribution — we can ship a whole group of classes as one unit (JAR file).

Creating a Package

To put a class in a package, the first statement in the file must be package packagename; (other than comments).

In simple words: The `package` statement must be the first statement in the file. Only comments may come before it — anything else is a compile error.

Compile it with the -d option so that the compiler creates the folder structure for the package:

Example03
Loading editor…

Creating a Package

This creates a folder mypack with Student.class inside it.

Example04
Loading editor…

Using a Package — import

To use a class from another package, write an import statement before your class.

Example05
Loading editor…

import vs fully qualified name

You can also use a class without import, by writing its full name with the package — this is called the fully qualified name:

Which is better? import is cleaner when you use the class many times. Fully qualified names are used when you need two classes with the same name from different packages — then you import one and fully qualify the other.

In simple words: A fully qualified name works without any import. Write the whole path like mypack.Student — it is the best choice when two packages have classes with the same name.
Example06
Loading editor…

Two Important Built-in Notes

  • The `java.lang` package is imported automatically into every program. That is why you can use String, System and Math without importing them.
  • The package name is usually written in small letters. Companies use their reverse domain name, e.g. com.google, org.apache.

Classpath and JAR

The classpath is the list of places where the JVM searches for your compiled classes. When your classes are not in the current folder, you tell Java where to look:

A JAR (Java Archive) is a single zip-like file that packages many .class files (and other resources) together. It makes distributing a program easy.

Example08
Loading editor…

Classpath and JAR

Example09
Loading editor…

Fully Qualified Example — Making It Real

Example10
Loading editor…

The Five Advantages of Packages

Why do we group classes into packages? The classic material gives five advantages:

AdvantageMeaning
ModularityRelated classes stay together as clean modules.
AbstractionUsers see only the public parts of a package, not its internals.
SecurityAccess modifiers control who can use what.
ReusabilityPackages can be used again in many applications.
SharabilityA package can be shared across projects and teams.

Important Predefined Packages

Java ships hundreds of ready-made packages. These are the ones you will use daily:

PackageWhat it provides
java.langBasics: String, Math, System, Object (auto-imported)
java.utilCollections, Scanner, Date, Random
java.ioReading and writing files, streams
java.netNetworking: Socket, URL
java.sqlDatabase: Connection, Statement
java.awtOld GUI components (heavyweight)
javax.swingModern GUI components (lightweight)
java.timeThe modern Date-Time API (Java 8+)

AWT vs Swing — A Package Question

This comparison is asked under the Packages chapter too. AWT components live in java.awt, Swing components in javax.swing:

PointAWT (java.awt)Swing (javax.swing)
ComponentsPlatform dependent (use OS components)Platform independent (Java draws them)
WeightHeavyweightLightweight
Components availableBasic: Button, TextField, LabelAdvanced: JTable, JTree, JColorChooser
PerformanceCan reduce performanceGenerally better
Which to useLegacy codeModern GUI work

Package Naming — The Domain Rule

Java recommends naming packages using your company domain in reverse, then project, then module. This keeps names unique worldwide.

Why reverse domain? If two companies both create a class Account, their packages com.example.Account and com.other.Account never clash.

Example14
Loading editor…

Packages and Imports — First Look

  • A package is a folder grouping related classes (java.io, java.util...). Two types: predefined (given by Java) and user-defined (made by you).
  • The package statement must be the first statement in the file (after comments). Only one package statement per file.
  • You can write any number of import statements.
  • import java.io.*; imports all classes of a package; import java.io.BufferedReader; imports one class.
  • You can even use a class without importing it — by writing its fully qualified name: java.io.BufferedReader br = new java.io.BufferedReader(...);
Example15
Loading editor…
📝 Key Takeaways
  • Package = folder that groups related classes; first statement of the file.
  • import mypack.*; brings in classes; java.lang is auto-imported.
  • Access levels: public (everywhere) > protected (package + children) > default (package) > private (class only).
  • Compile packages with javac -d . to create folder structure.
  • Classpath tells JVM where classes live; jar packages many classes into one file.
  • Reverse-domain package names (com.company.app) keep large projects safe from clashes.

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.