Java - Packages and Java Modules

1. What are Packages in Java?

A package in Java is a namespace used to organize classes and interfaces into groups. It helps structure large programs and avoid name conflicts between classes.

In simple terms, packages are like folders that store related classes together.

Examples of built-in packages:

  • java.lang

  • java.util

  • java.io


2. Why Use Packages?

  • Organizes code into logical groups

  • Prevents class name conflicts

  • Improves maintainability

  • Provides access control through visibility rules

Packages are especially useful when working on large projects.


3. Creating a Package

You create a package using the package keyword at the beginning of a program.

package mypackage; public class Test { public void show() { System.out.println("Hello"); } }

This places the class inside the mypackage namespace.


4. Using Packages

To use classes from another package, you import them.

import java.util.Scanner;

Or import everything:

import java.util.*;

You can also use fully qualified names without importing.

java.util.Scanner s = new java.util.Scanner(System.in);

5. Access Control in Packages

Java provides access modifiers to control visibility:

  • public — accessible everywhere

  • protected — accessible within package and subclasses

  • default — accessible within same package only

  • private — accessible within the same class

This helps secure and structure code.


6. What are Java Modules?

Java modules were introduced in Java 9 to provide stronger organization and dependency management than packages.

A module is a collection of packages grouped together with defined access rules. Modules improve:

  • Security

  • Maintainability

  • Performance

They allow developers to explicitly state which packages are accessible.


7. Module Descriptor File

Modules use a file called module-info.java.

Example:

module mymodule { exports com.example.util; }

This exports a package so other modules can use it.


8. Advantages of Modules

  • Better encapsulation

  • Explicit dependency control

  • Faster startup and smaller runtime images

  • Improved scalability for large applications


Summary

Packages organize classes into logical groups, while modules provide higher-level organization by grouping packages and controlling dependencies between them. Together, they help structure large Java applications in a clean and secure way.