Packages and Modules

Back

Loading concept...

📦 Packages and Modules: Organizing Your Java World

Imagine you have a giant toy box with thousands of toys. Finding your favorite car would be a nightmare! But what if you had smaller boxes inside—one for cars, one for dolls, one for building blocks? That’s exactly what packages do for Java code!


🏠 The Big Picture

Think of your Java code like a huge city. Without organization:

  • Streets have no names
  • Houses have no addresses
  • You’d never find anything!

Packages are like neighborhoods in this city. Each neighborhood has a name, and houses (classes) inside have addresses (package names). Later, Java added modules—think of them as entire districts that group neighborhoods together!

graph TD A["🏙️ Your Java City"] --> B["📁 Package: vehicles"] A --> C["📁 Package: animals"] B --> D["🚗 Car.java"] B --> E["🚲 Bike.java"] C --> F["🐕 Dog.java"] C --> G["🐱 Cat.java"]

📁 Packages: Your Code’s Home Address

What is a Package?

A package is a folder that groups related Java classes together. It gives your class a unique address so Java knows exactly where to find it.

Real Life Example:

  • Without packages: You say “I live in House 5” — but which city? Which street?
  • With packages: You say “I live at 5 Oak Street, Springfield, USA” — crystal clear!

Creating a Package

// File: Car.java
package vehicles;

public class Car {
    public void drive() {
        System.out.println("Vroom!");
    }
}

What happened?

  1. package vehicles; — This tells Java: “Put this Car class in the vehicles folder”
  2. The file must live in a folder called vehicles/

Package Naming Rules

Rule Example Why?
All lowercase mypackage Easy to read
No spaces my_package Computers don’t like spaces
Reverse domain com.google.maps Ensures uniqueness worldwide

Pro Tip: Big companies use their website backwards:

  • Google’s packages: com.google.something
  • Your packages: com.yourname.project

📬 Import Statements: Sending Invitations

The Problem

Imagine you’re in the animals neighborhood and want to use a Car from vehicles. You can’t just say “Car”—Java won’t know which Car you mean!

The Solution: Import

// File: Dog.java in animals package
package animals;

import vehicles.Car;  // Hey Java, bring Car here!

public class Dog {
    public void ride() {
        Car myCar = new Car();
        myCar.drive();
    }
}

Types of Imports

1. Single Class Import (Most Common)

import java.util.ArrayList;
// Brings just ArrayList

2. Wildcard Import (Brings Everyone)

import java.util.*;
// Brings ALL classes from java.util

3. Static Import (For Constants & Methods)

import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

// Now you can write:
double area = PI * r * r;
double root = sqrt(16);

What You DON’T Need to Import

Java automatically imports:

  • Everything in java.lang (String, System, Math…)
  • Classes in the same package as your file
graph TD A["Your Class"] --> B{Need Import?} B -->|Same Package| C["NO ✅"] B -->|java.lang| D["NO ✅"] B -->|Different Package| E["YES 📬"]

🛤️ Classpath: Java’s GPS

What is Classpath?

When you say import vehicles.Car, Java thinks:

“Where do I find this vehicles folder?”

The classpath is Java’s GPS—it tells Java where to look for classes!

Setting the Classpath

From Command Line:

# On Mac/Linux
java -cp /home/code:/libs/helper.jar MyApp

# On Windows
java -cp C:\code;C:\libs\helper.jar MyApp

Breaking it down:

  • -cp or -classpath = “Here’s where to look”
  • Separate multiple paths with : (Mac/Linux) or ; (Windows)

Visual Example

Your Project
├── src/
│   ├── vehicles/
│   │   └── Car.java
│   └── Main.java
└── libs/
    └── helper.jar

To run Main.java that uses both Car and classes from helper.jar:

java -cp src:libs/helper.jar Main

Common Classpath Mistakes

Mistake What Happens Fix
Forgot to add path ClassNotFoundException Add the folder to classpath
Wrong separator Classes not found Use : (Mac/Linux) or ; (Windows)
Missing JAR NoClassDefFoundError Include the JAR file

🫙 JAR Files: Zipping Your Classes

What is a JAR?

JAR = Java ARchive

It’s like a ZIP file for Java classes! Instead of sharing 100 separate .class files, you bundle them into one .jar file.

Real Life:

  • Without JAR: Sending 50 photos one by one 📧📧📧📧📧
  • With JAR: Sending one ZIP with all 50 photos 📦

Creating a JAR

Step 1: Compile your classes

javac vehicles/*.java

Step 2: Bundle into JAR

jar cvf vehicles.jar vehicles/*.class

What do those letters mean?

  • c = create a new JAR
  • v = verbose (show what’s happening)
  • f = file name comes next

Using a JAR

# Run a program using classes from mylib.jar
java -cp mylib.jar:. MyProgram

What’s Inside a JAR?

mylib.jar
├── vehicles/
│   ├── Car.class
│   └── Bike.class
├── animals/
│   └── Dog.class
└── META-INF/
    └── MANIFEST.MF  ← Special info file

The MANIFEST.MF File

This special file tells Java important things:

Manifest-Version: 1.0
Main-Class: vehicles.Car
Created-By: 17 (Oracle)

Main-Class = Which class to run when you double-click the JAR!

Making a Runnable JAR

# Create JAR with main class specified
jar cvfe myapp.jar Main Main.class

# Run it simply with:
java -jar myapp.jar

🧱 Module System Basics: The Next Level

Why Modules?

Packages group classes. But what if you have thousands of packages? You need to group packages too!

Analogy:

  • Class = A single house 🏠
  • Package = A neighborhood 🏘️
  • Module = An entire district 🌆

The Big Problem Modules Solve

Before modules, any code could access any package. It was like having no locks on any door! Modules add:

  • Strong encapsulation — Hide packages you don’t want others to use
  • Reliable dependencies — Know exactly what your code needs

Creating a Module

Step 1: Create module-info.java in your source root

// module-info.java
module com.myapp {
    requires java.sql;      // I need this!
    exports com.myapp.api;  // Others can use this!
}

Step 2: Organize your code

src/
└── com.myapp/
    ├── module-info.java
    └── com/
        └── myapp/
            ├── api/
            │   └── PublicStuff.java
            └── internal/
                └── SecretStuff.java

Module Keywords

Keyword What It Does Example
module Declares a module module myapp { }
requires “I need this module” requires java.sql;
exports “Others can use this package” exports com.api;
opens “Allow reflection on this” opens com.internal;

Visual: How Modules Work

graph LR A["Module A"] -->|requires| B["Module B"] B -->|exports api| A B -.->|hides internal| A style A fill:#e1f5fe style B fill:#fff3e0

Compiling & Running Modules

# Compile
javac -d out --module-source-path src \
    $(find src -name "*.java")

# Run
java --module-path out -m com.myapp/com.myapp.Main

Built-in Java Modules

Java itself is now modular! Some key modules:

Module Contains
java.base Core classes (auto-included)
java.sql Database connectivity
java.desktop GUI (Swing, AWT)
java.logging Logging framework

🎯 Quick Summary

Concept What It Is One-Line Explanation
Package Folder for classes Gives your class a unique address
Import Bringing in classes “Hey Java, I need this class!”
Classpath Search path Tells Java where to find classes
JAR Bundled classes ZIP file for Java code
Module Group of packages Strong boundaries + clear dependencies

🚀 You Did It!

You now understand how Java organizes code from small (classes) to big (modules):

graph TD A["📄 Class"] -->|grouped in| B["📁 Package"] B -->|grouped in| C["🧱 Module"] C -->|bundled as| D["🫙 JAR"] D -->|found via| E["🛤️ Classpath"]

Remember: Good organization isn’t just neat—it’s what makes building huge, reliable software possible!


Next time you write import, you’ll know exactly what’s happening behind the scenes. That’s the power of understanding packages and modules! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.