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
JCode Cell
1java.lang -> String, Math, System (basic classes)
2java.util -> ArrayList, HashMap, Scanner
3java.io -> File, FileInputStream
4java.net -> Socket, URL
5java.sql -> Connection, Statement

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
JCode Cell
1package mypack; // must be the first statement
2 
3public class Student {
4 public void display() {
5 System.out.println("Student from mypack");
6 }
7}

Creating a Package

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

Example04
JCode Cell
1javac -d . Student.java

Using a Package — import

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

Example05
JCode Cell
1import mypack.Student; // import only Student
2// OR
3import mypack.*; // import all classes of mypack
4 
5class Test {
6 public static void main(String[] args) {
7 Student s = new Student();
8 s.display();
9 }
10}
Output
Student from mypack

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
JCode Cell
1class Test {
2 public static void main(String[] args) {
3 mypack.Student s = new mypack.Student(); // no import needed
4 s.display();
5 }
6}

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
JCode Cell
1java -cp mypack;classes Test
2 
3// or set it once in Environment Variables as CLASSPATH

Classpath and JAR

Example09
JCode Cell
1jar -cf mylib.jar mypack/ // create jar
2jar -tf mylib.jar // list jar contents
3java -cp mylib.jar Test // run using the jar

Fully Qualified Example — Making It Real

Example10
JCode Cell
1// File: mypack/Calculator.java
2package mypack;
3 
4public class Calculator {
5 public int add(int a, int b) { return a + b; }
6}
7 
8// File: Test.java
9import mypack.Calculator;
10 
11class Test {
12 public static void main(String[] args) {
13 Calculator c = new Calculator();
14 System.out.println("Sum = " + c.add(10, 20));
15 }
16}
Output
Sum = 30

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
JCode Cell
1Website : www.example.com
2Reverse : com.example
3 
4package com.example.icici.transactions.deposit;
5| | | | |
6| | | | +-- sub module
7| | | +-- module name
8| | +-- project / client name
9| +-- company domain in reverse
10+-- always starts with com/org/net etc.

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
JCode Cell
1// With import
2import java.io.*;
3BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
4 
5// Without import (fully qualified name)
6java.io.BufferedReader br = new java.io.BufferedReader(
7 new java.io.InputStreamReader(System.in));
📝 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