Skip to content

Packages in Java

A package in Java is a namespace that organizes related classes and interfaces, preventing naming conflicts and promoting modular code organization. Packages in Java act as containers for classes, interfaces, and sub-packages, enabling better management of code.


Key Features of Packages

  1. Organized Code:
    1. Helps group related classes and interfaces together.
  2. Namespace Management:
    1. Avoids naming conflicts by providing a unique namespace.
  3. Access Protection:
    1. Controls access levels using access modifiers (public, protected, default, private).
  4. Reusable Code:
    1. Enables reusability by importing pre-written packages.

Types of Packages in Java

  1. Built-in Packages:
    1. Java provides pre-defined packages such as:
      1. java.util (e.g., ArrayList, HashMap)
      1. java.io (e.g., File, BufferedReader)
      1. java.net (e.g., Socket, URL)
  2. User-defined Packages:
    1. Created by developers to organize their application code.

Creating a Package

To create a package, use the package keyword at the top of your Java file.

Steps:

  1. Define the package name.
  2. Save the file in a directory matching the package name.

Example:

package mypackage;

public class MyClass {

    public void displayMessage() {

        System.out.println(“Hello from MyClass in mypackage!”);

    }

}

  • Save this file as MyClass.java in a folder named mypackage.

Using a Package

Importing a Package

  1. Explicit Import:
    1. Imports a specific class or interface:

import mypackage.MyClass;

  • Wildcard Import:
    • Imports all classes in the package:

import mypackage.*;

Accessing a Class from the Package

import mypackage.MyClass;

public class Main {

    public static void main(String[] args) {

        MyClass obj = new MyClass();

        obj.displayMessage();

    }

}


Compiling and Running a Package

  1. Compilation:
    1. Use the -d option to specify the base directory for the package structure:

javac -d . MyClass.java

  • This creates the mypackage directory and places the compiled .class file inside it.
  • Execution:
    • Navigate to the base directory and use the fully qualified name:

java mypackage.MyClass


Access Modifiers in Packages

ModifierSame PackageDifferent Package (Subclass)Different Package (Non-Subclass)
publicYesYesYes
protectedYesYesNo
defaultYesNoNo
privateNoNoNo

Built-in Package Example

Using java.util.ArrayList

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add(“Apple”);

        list.add(“Banana”);

        System.out.println(list);

    }

}


User-defined Package Example

Creating the Package

package utilities;

public class Calculator {

    public int add(int a, int b) {

        return a + b;

    }

}

Using the Package

import utilities.Calculator;

public class Main {

    public static void main(String[] args) {

        Calculator calc = new Calculator();

        System.out.println(“Sum: ” + calc.add(5, 10));

    }

}


Advantages of Using Packages

  1. Modularity:
    1. Promotes separation of concerns by grouping related classes.
  2. Reusability:
    1. Allows developers to reuse packages across multiple projects.
  3. Avoids Name Conflicts:
    1. Different packages can have classes with the same name.
  4. Access Control:
    1. Controls the visibility of classes and methods.

Best Practices

  1. Use Meaningful Names:
    1. Use descriptive package names to reflect their functionality (e.g., com.myapp.utils).
  2. Follow Naming Conventions:
    1. Package names are typically written in lowercase to avoid conflicts with class names.
  3. Modular Design:
    1. Divide functionality into smaller, manageable packages.

Conclusion

Packages are a fundamental feature in Java for organizing and managing code effectively. They help developers create modular, reusable, and maintainable software systems while avoiding naming conflicts and improving access control. Both built-in and user-defined packages are powerful tools in Java’s programming ecosystem.