Great topic, Sudhakar! Let's explore packages in Java — they're essential for organizing code, avoiding name conflicts, and building clean, modular applications.
📦 What is a Package in Java?
A package in Java is a namespace that organizes related classes and interfaces.
You can think of it like a folder in your computer that holds similar files — it helps keep your codebase clean and manageable.
✅ Types of Packages
1. Built-in Packages
Provided by Java itself.
Examples:
-
java.lang(default – includesString,Math, etc.) -
java.util(collections, date/time, etc.) -
java.io(file input/output) -
java.sql(database connectivity)
import java.util.Scanner; // importing built-in class2. User-defined Packages
You can create your own packages to group related classes.
🧠 Creating and Using a Package
🔨 Step 1: Create the Package
File: MyClass.java
package mypackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypackage!");
}
}Note: The package line must be the first line of code.
🔗 Step 2: Use the Package in Another File
File: Test.java
import mypackage.MyClass;
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}⚙️ Compile & Run (Command Line):
javac -d . MyClass.java // creates folder structure for package
javac Test.java
java Test🧾 Benefits of Using Packages
| Benefit | Description |
|---|---|
| ✅ Organization | Helps group related classes |
| ✅ Avoids name conflicts | Two classes with the same name can live in different packages |
| ✅ Access control | Use public, private, protected, and default access wisely |
| ✅ Code reusability | Easier to import and reuse functionality |
🔐 Access Modifiers with Packages
| Modifier | Same Class | Same Package | Subclass (Other Package) | Other Package |
|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ | ❌ |
| no modifier | ✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ |
🎯 Real-World Example:
com.bank.accounts.SavingsAccountcom.bank.transactions.TransferService
These packages help break down a project into meaningful modules.