← Back to Home

Packages in Java

A package in Java is a namespace that groups related classes and interfaces together. Packages help organize large applications, avoid naming conflicts, control access, and improve maintainability. This is a high-frequency interview topic and fundamental to real-world Java project structure.

What Is a Package?

  • A logical container for classes and interfaces
  • Provides a namespace
  • Supports access control
  • Improves code organization and reuse
package com.company.project.module;
          

Why Packages Are Needed

  • Organize large codebases
  • Avoid class name conflicts
  • Control visibility using access modifiers
  • Enable modular development
  • Improve readability and maintenance

Types of Packages in Java

1️⃣ Built-in Packages

Provided by Java standard library.

Examples:

  • java.lang
  • java.util
  • java.io
  • java.sql
  • java.time

✔ Automatically available:

java.lang.*
          

2️⃣ User-Defined Packages

Created by developers to organize application code.

package com.bank.account;
          

Creating a Package

1. Using package Keyword

package com.example.util;

public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}
          

Rules:

  • package statement must be first line
  • Only one package statement per class

2. Compile with Directory Structure

javac -d . MathUtil.java
          

✔ Creates folder structure automatically

Package Naming Conventions (Very Important)

  • All lowercase
  • Reverse domain name format
com.company.project.module
          

Examples:

  • com.google.common
  • org.apache.commons

Accessing Classes from a Package

1. Using Fully Qualified Name

com.example.util.MathUtil.add(2, 3);
          

2. Using import Statement

import com.example.util.MathUtil;

MathUtil.add(2, 3);
          

3. Import All Classes (Wildcard)

import com.example.util.*;
          

⚠️ Imports only classes, not sub-packages

Access Modifiers and Packages (Interview Favorite)

Modifier Same Class Same Package Subclass (diff pkg) Everywhere
private
default
protected
public

✔ Packages define visibility boundaries

Sub-Packages

com.company
 └── util
 └── service
          
  • ✔ Sub-packages are independent
  • ✔ No automatic access between parent and child packages

Static Import (Java 5+)

Allows direct access to static members.

import static java.lang.Math.*;

double r = sqrt(16);
          
  • ✔ Improves readability
  • ⚠️ Use sparingly

Package vs Folder (Clarification)

Aspect Package Folder
Concept Logical grouping Physical directory
Java-level Yes No
Naming Namespace File system
Relation Often mapped Not mandatory

JAR and Packages

  • Packages are bundled into JAR files
  • JARs are used for distribution and reuse
jar cf utils.jar com/example/util/*.class
          

Common Beginner Mistakes

  • Forgetting package statement
  • Incorrect folder structure
  • Using uppercase letters in package names
  • Assuming sub-packages inherit access
  • Overusing wildcard imports

Interview-Ready Answers

Short Answer

A package is a namespace that groups related classes and interfaces in Java.

Detailed Answer

In Java, packages are used to organize classes and interfaces into logical units, prevent naming conflicts, and control access using access modifiers. Java provides built-in packages, and developers can create custom packages using the package keyword.

Key Takeaway

Packages bring structure, safety, and scalability to Java applications. They are essential for clean architecture, modular development, and enterprise-level codebases.

Package Examples (Quick Reference)

1. Using a Built-in Package (java.util)

import java.util.ArrayList;

class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        System.out.println(list);
    }
}
          

Output

[Java]

2. Fully Qualified Class Name (No import)

class Demo {
    public static void main(String[] args) {
        java.util.Date d = new java.util.Date();
        System.out.println(d);
    }
}
          

Explanation

  • Avoids import
  • Used when class name conflicts exist

3. User-Defined Package Creation

package com.app.util;

public class Helper {
    public static void help() {
        System.out.println("Helping");
    }
}
          

4. Using a User-Defined Package Class

import com.app.util.Helper;

class Demo {
    public static void main(String[] args) {
        Helper.help();
    }
}
          

Output

Helping

5. Package with Multiple Classes

package com.app.model;

public class User {
    public String name = "Admin";
}

package com.app.model;

public class Role {
    public String role = "ADMIN";
}
          

6. Accessing Multiple Classes from Same Package

import com.app.model.User;
import com.app.model.Role;

class Demo {
    public static void main(String[] args) {
        User u = new User();
        Role r = new Role();
        System.out.println(u.name + " - " + r.role);
    }
}
          

Output

Admin - ADMIN

7. import package.* Usage

import java.util.*;

class Demo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(10);
        System.out.println(list);
    }
}
          

Explanation

  • Imports all public classes
  • Not recommended for large projects

8. Same Class Name in Different Packages

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

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

9. Resolving Name Conflict Using Fully Qualified Name

class Demo {
    public static void main(String[] args) {
        p1.Test t1 = new p1.Test();
        p2.Test t2 = new p2.Test();
        t1.show();
        t2.show();
    }
}
          

Output

p1 Test
p2 Test
          

10. Default Package (No Package)

class Demo {
    public static void main(String[] args) {
        System.out.println("Default package");
    }
}
          

Explanation

  • No package statement
  • Not recommended for real projects

11. Accessing Default Package Class (Not Allowed)

// From a named package
package com.test;

// class Demo {
//     DefaultClass d; // ❌ not accessible
// }
          

Explanation

Classes in default package cannot be imported.

12. Package + public Access Modifier

package com.app;

public class A {
    public void show() {
        System.out.println("Public method");
    }
}

import com.app.A;

class Demo {
    public static void main(String[] args) {
        new A().show();
    }
}
          

Output

Public method

13. Package + Default (No Modifier) Access

package com.app;

class A {
    void show() {
        System.out.println("Default access");
    }
}

// From another package
// new com.app.A().show(); // ❌ not accessible
          

Explanation

Default access → same package only.

14. Package + protected Access

package p1;

public class A {
    protected void show() {
        System.out.println("Protected");
    }
}

package p2;

import p1.A;

class B extends A {
    public static void main(String[] args) {
        new B().show();
    }
}
          

Output

Protected

15. Package Structure on Disk

src/
 └── com/
     └── app/
         └── util/
             └── Helper.java
          

Explanation

Directory structure must match package name.

16. Compiling Package Code

javac -d . Helper.java

Explanation

-d creates directory structure automatically.

17. Creating a JAR from Package

jar cf util.jar com/app/util/*.class

Explanation

Packages are bundled into JARs.

18. Using Package from JAR

javac -cp util.jar Demo.java
java  -cp .;util.jar Demo
          

19. Static Import from Package

import static java.lang.Math.sqrt;

class Demo {
    public static void main(String[] args) {
        System.out.println(sqrt(16));
    }
}
          

Output

4.0

20. Interview Summary – Packages

package com.demo;

public class Test {
    public static void main(String[] args) {
        System.out.println("Package demo");
    }
}
          

Key Points

  • Groups related classes & interfaces
  • Avoids naming conflicts
  • Controls access
  • Improves maintainability

Output

Package demo