DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 3 — Packages in Java

As Java applications grow, managing hundreds or even thousands of classes becomes challenging.

Imagine having every class in one folder with names like:

Student
Customer
Order
Payment
Invoice
Employee
Manager
Enter fullscreen mode Exit fullscreen mode

Now imagine another library also contains a class named Student.

How would Java know which one you mean?

This is exactly why packages exist.

Packages help organize related classes, avoid naming conflicts, improve modularity, and provide better access control.

In this article, you'll learn:

  • What packages are
  • Why we use them
  • Package declaration rules
  • Naming conventions
  • How to compile and run package programs
  • Common interview questions
  • Best practices

What Is a Package?

A package is a namespace used to group related classes, interfaces, enums, records, and annotations.

Think of a package like a folder on your computer.

Example:

com
└── rajesh
    └── learning
        ├── Student.java
        ├── Employee.java
        ├── Customer.java
        └── Order.java
Enter fullscreen mode Exit fullscreen mode

Instead of keeping everything in one place, Java organizes related classes into packages.


Why Do We Need Packages?

Packages solve several important problems.

1. Avoid Naming Conflicts

Different libraries may contain classes with the same name.

Example:

com.company.hr.Employee
Enter fullscreen mode Exit fullscreen mode

and

com.company.payroll.Employee
Enter fullscreen mode Exit fullscreen mode

Both classes are named Employee, but they belong to different packages.

Without packages, Java wouldn't know which one you mean.


2. Improve Code Organization

Instead of placing every class in one folder, related classes stay together.

Example:

com.rajesh.orders
Enter fullscreen mode Exit fullscreen mode

contains order-related classes.

com.rajesh.payment
Enter fullscreen mode Exit fullscreen mode

contains payment-related classes.

This makes projects much easier to navigate.


3. Improve Modularity

Large applications are divided into independent modules.

Example:

com.rajesh.user
com.rajesh.inventory
com.rajesh.billing
com.rajesh.notification
Enter fullscreen mode Exit fullscreen mode

Each package has a specific responsibility.


4. Provide Better Access Control

Packages work together with Java's access modifiers.

Classes in the same package can access package-private members, helping encapsulate implementation details.


Package Declaration

A package is declared using the package keyword.

Example

package com.rajesh.learning;
Enter fullscreen mode Exit fullscreen mode

This statement tells the compiler that the class belongs to the package:

com.rajesh.learning
Enter fullscreen mode Exit fullscreen mode

Complete Example

package com.rajesh.learning;

public class Student {

    public static void main(String[] args) {

        System.out.println("Welcome, Rajesh!");

    }

}
Enter fullscreen mode Exit fullscreen mode

Where Should the Package Statement Appear?

The package statement must be the first non-comment statement in the file.

Correct

package com.rajesh.learning;

import java.util.ArrayList;

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

Incorrect

import java.util.ArrayList;

package com.rajesh.learning;

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error.


Can We Have Multiple Package Statements?

No.

This is illegal.

package com.rajesh.learning;

package com.rajesh.demo;

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

Compile-time error.

A Java source file can contain at most one package statement.


Package Naming Convention

Package names are usually written in lowercase.

Most organizations use their internet domain name in reverse order.

Examples

com.google.gson
Enter fullscreen mode Exit fullscreen mode
org.springframework.boot
Enter fullscreen mode Exit fullscreen mode
com.oracle.jdbc
Enter fullscreen mode Exit fullscreen mode

For personal projects, you might use:

com.rajesh.learning
Enter fullscreen mode Exit fullscreen mode

or

io.rajesh.demo
Enter fullscreen mode Exit fullscreen mode

This naming convention reduces the chance of naming conflicts.


Default Package

If no package statement is present, the class belongs to the default package.

Example

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

This class belongs to the default package.

Although convenient for learning, the default package should be avoided in real-world applications.


Compiling a Package Program

Suppose we have:

package com.rajesh.learning;

public class Student {

    public static void main(String[] args) {

        System.out.println("Package Demo");

    }

}
Enter fullscreen mode Exit fullscreen mode

File name:

Student.java
Enter fullscreen mode Exit fullscreen mode

Option 1

Compile normally.

javac Student.java
Enter fullscreen mode Exit fullscreen mode

The class file is created in the current directory.

However, the package folder structure is not created automatically.


Option 2 (Recommended)

Use the -d option.

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

Here,

  • -d means destination
  • . means current directory

Java automatically creates the folder structure.

Result

com
└── rajesh
    └── learning
        └── Student.class
Enter fullscreen mode Exit fullscreen mode

This is the recommended approach.


Using Another Destination

You can specify any valid directory.

Example

javac -d C:\Projects Student.java
Enter fullscreen mode Exit fullscreen mode

The package structure will be created inside:

C:\Projects
Enter fullscreen mode Exit fullscreen mode

If the destination doesn't exist, compilation fails.


Running a Package Program

When executing a package program, always use the fully qualified class name.

Suppose the package is:

com.rajesh.learning
Enter fullscreen mode Exit fullscreen mode

Run it like this:

java com.rajesh.learning.Student
Enter fullscreen mode Exit fullscreen mode

Do not run

java Student
Enter fullscreen mode Exit fullscreen mode

because the JVM searches using the package name.


Package Folder Structure

Given

package com.rajesh.learning;
Enter fullscreen mode Exit fullscreen mode

the compiled class should be stored as

com
└── rajesh
    └── learning
        └── Student.class
Enter fullscreen mode Exit fullscreen mode

Notice that the folder structure matches the package declaration exactly.


Common Beginner Mistakes

Forgetting to Use the Fully Qualified Name

Incorrect

java Student
Enter fullscreen mode Exit fullscreen mode

Correct

java com.rajesh.learning.Student
Enter fullscreen mode Exit fullscreen mode

Package Name Doesn't Match Folder Structure

If your package is

package com.rajesh.learning;
Enter fullscreen mode Exit fullscreen mode

the compiled class should be inside

com/rajesh/learning
Enter fullscreen mode Exit fullscreen mode

Otherwise, the JVM won't find it.


Multiple Package Statements

Only one package statement is allowed.


Package Statement After Import

Incorrect

import java.util.*;

package com.rajesh.learning;
Enter fullscreen mode Exit fullscreen mode

The package statement must come first.


Interview Questions

Can a Java source file contain multiple package statements?

No.

Only one package statement is allowed.


Is the package statement mandatory?

No.

If omitted, the class belongs to the default package.


Where should the package statement appear?

It must be the first non-comment statement.


Why do companies use reverse domain names?

To avoid naming conflicts.

Example

com.oracle
Enter fullscreen mode Exit fullscreen mode
org.springframework
Enter fullscreen mode Exit fullscreen mode

Which command automatically creates the package directory structure?

javac -d .
Enter fullscreen mode Exit fullscreen mode

How do you execute a package program?

Using the fully qualified class name.

Example

java com.rajesh.learning.Student
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Always organize production code into packages.
  • Use lowercase package names.
  • Follow the reverse domain naming convention.
  • Avoid the default package in real projects.
  • Keep related classes in the same package.
  • Use javac -d while compiling package programs.

Quick Memory Trick 🧠

Remember:

Package = Folder = Organization

Or simply:

Packages organize. Imports locate. Classes implement.


Key Takeaways

  • Packages organize related classes and interfaces.
  • They prevent naming conflicts.
  • Package declarations are optional but recommended.
  • Only one package statement is allowed.
  • The package statement must be the first non-comment statement.
  • Package names usually follow the reverse domain convention.
  • Use javac -d to create the correct directory structure.
  • Execute package programs using the fully qualified class name.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)