Table of contents
1.
Introduction
2.
What is a Package in Java?
3.
Why Use Packages in Java?
4.
How Packages Work in Java
4.1.
Organize Code:
4.2.
Avoid Name Conflicts:
4.3.
Access Control:
4.4.
Package Declaration:
4.5.
Importing Packages:
4.6.
Built-in Packages:
4.7.
Custom Packages:
4.8.
Folder Structure:
5.
Types of Packages in Java
5.1.
Built-in Packages in Java
5.2.
User-defined Packages in Java
5.3.
Using Static Import
5.4.
Handling name conflicts
5.5.
Directory structure
5.6.
Subpackage in Java
5.7.
Advantages of packages
5.8.
Accessing a package
6.
Frequently Asked Questions
6.1.
What is the difference between a package and a class in Java?
6.2.
What are user-defined packages in Java?
6.3.
How many packages are in Java?
7.
Conclusion
Last Updated: Mar 30, 2025
Easy

Packages in Java

Author NISHANT RANA
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Packages can be considered folders in the directory. They store classes, interfaces, and sub-packages of similar types. They are the main part of the encapsulation process, helping to encapsulate data of the same type.

 Packages in Java

This article provides a detailed explanation of Java packages, their purpose, types, and benefits in organizing Java programs efficiently.

What is a Package in Java?

Java package is a mechanism for organizing related classes, interfaces, and sub-packages into a structured hierarchy. It helps in avoiding name conflicts, improving code maintainability, and providing access control.

Why Use Packages in Java?

  1. Avoids Name Conflicts – Prevents class name collisions by grouping them into different namespaces.
  2. Code Reusability – Allows reuse of existing classes across different programs.
  3. Access Control – Provides controlled access to classes using access modifiers.
  4. Better Maintainability – Simplifies project management by logically grouping related functionalities.
  5. Encapsulation – Enhances security by restricting access to package-level classes.

How Packages Work in Java

Packages in Java are used to group related classes, interfaces, and sub-packages. Here’s how packages work:

Organize Code:

Packages provide a mechanism to organize classes and interfaces into namespaces, making it easier to maintain and navigate large codebases.

Avoid Name Conflicts:

By grouping related classes into a package, Java helps avoid naming conflicts between classes in different packages. For example, two classes with the same name can coexist in different packages.

Access Control:

Packages define access levels for classes and methods. The default access modifier allows access to classes within the same package but restricts access from other packages.

Package Declaration:

At the start of a Java file, the package is declared using the package keyword. For example:

package com.example;

Importing Packages:

Classes from other packages can be imported using the import statement. This allows the use of classes from one package in another.

import com.example.MyClass;

Built-in Packages:

Java provides many built-in packages like java.util, java.io, and java.lang, which contain utility classes for data structures, input/output operations, and core functionalities.

Custom Packages:

Developers can create custom packages to organize project-specific classes. For example:

package myapp.utilities;

Folder Structure:

Each package corresponds to a folder in the file system. For example, a package com.example will be located in the com/example directory.

Types of Packages in Java

There are two types of packages:-

  1. Built-in packages: The packages which are already present in java are known as built-in packages. For example, util, io, lang, etc.
     
  2. User-defined packages: The packages which are made by the users are known as user-defined packages.

Built-in Packages in Java

Java provides a rich set of built-in packages that contain classes for common functionalities such as data structures, input/output, and networking. These packages are part of the core Java library.

Common Built-in Packages:

  • java.lang: Contains fundamental classes like String, Math, and Object. It is automatically imported.
     
  • java.util: Provides utility classes such as ArrayList, HashMap, and date-time utilities.
     
  • java.io: This contains classes for input and output operations like FileReader, BufferedReader, and FileOutputStream.
     
  • java.net: Includes classes for networking, such as URL, Socket, and HttpURLConnection.

Implementation:

// Example using java.util package
import java.util.ArrayList;
public class BuiltInPackageExample {
   public static void main(String[] args) {
       ArrayList<String> list = new ArrayList<>();
       list.add("Java");
       list.add("Python");
       list.add("C++");
       System.out.println("Programming Languages: " + list);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

Programming Languages: [Java, Python, C++]

User-defined Packages in Java

User-defined packages are created by developers to organize classes and interfaces into a custom namespace. This helps manage large projects by grouping related components logically.

Syntax:

package mypackage;


Example Code:

// Define a package named mypackage
package mypackage;
public class MyClass {
   public void display() {
       System.out.println("This is a user-defined package example.");
   }
}
You can also try this code with Online Java Compiler
Run Code
// Use the package in another file
import mypackage.MyClass;
public class TestPackage {
   public static void main(String[] args) {
       MyClass obj = new MyClass();
       obj.display();
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

This is a user-defined package example.

Using Static Import

Static Import in Java allows you to access static members (fields and methods) of a class without qualifying them with the class name. This can make the code cleaner and easier to read.
Implementation:

import static java.lang.Math.*;
public class StaticImportExample {
   public static void main(String[] args) {
       double result = sqrt(25); // Using static import for sqrt() method
       System.out.println("Square root of 25 is: " + result);
       
       double piValue = PI; // Using static import for PI constant
       System.out.println("Value of PI is: " + piValue);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

Square root of 25 is: 5.0
Value of PI is: 3.141592653589793

Handling name conflicts

When two classes have methods or fields with the same name, it can lead to naming conflicts. You can resolve this by fully qualifying the method or field with the class name.

Implementation

class ClassA {
   static void display() {
       System.out.println("Display from ClassA");
   }
}
class ClassB {
   static void display() {
       System.out.println("Display from ClassB");
   }
}
public class NameConflictExample {
   public static void main(String[] args) {
       ClassA.display(); // Call display() from ClassA
       ClassB.display(); // Call display() from ClassB
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Display from ClassA
Display from ClassB

Directory structure

In Java, packages correspond to a directory structure on the file system. This means the directory names represent the package names, allowing the Java compiler to locate classes easily.

Example Directory Structure:

src/
   com/
       example/
           MyClass.java
           TestClass.java


Implementation:

// File: src/com/example/MyClass.java
package com.example;
public class MyClass {
   public void display() {
       System.out.println("This is MyClass in com.example package.");
   }
}
// File: src/com/example/TestClass.java
package com.example;
public class TestClass {
   public static void main(String[] args) {
       MyClass obj = new MyClass();
       obj.display();
   }
}


Output

This is MyClass in com.example package.

Subpackage in Java

A subpackage is a package within another package, which helps to further organize classes logically.

Example:

  • Directory Structure:
src/
   com/
       example/
           main/
               MainClass.java
           utils/
               UtilityClass.java


Implementation

// File: src/com/example/utils/UtilityClass.java
package com.example.utils;
public class UtilityClass {
   public static void show() {
       System.out.println("UtilityClass method called.");
   }
}
// File: src/com/example/main/MainClass.java
package com.example.main;
import com.example.utils.UtilityClass; // Importing from subpackage
public class MainClass {
   public static void main(String[] args) {
       UtilityClass.show(); // Calling method from subpackage
   }
}


Output:

UtilityClass method called.

Advantages of packages

  1. They help in encapsulating similar classes and interfaces.
     
  2. They help in avoiding the errors caused due same names of the classes.
     
  3. It makes searching and usage of the classes, interfaces, and sub-packages easy.
     
  4. It also provides security by not allowing unauthorized access. The private or protected variables, classes can not be accessed outside the same package.
     

We generally use the package keyword to make a package as follows:-

package CodingNinjas;

public class Main{
    public static void main(String args[]){  
        System.out.println("Hey..");
    }  
}
You can also try this code with Online Java Compiler
Run Code


We need to run the following command to compile any java code:

javac -d directory javafilename  
You can also try this code with Online Java Compiler
Run Code


For the above code we need to write:-

javac -d . Main.java  
You can also try this code with Online Java Compiler
Run Code


After running the above command a class named Main will be made under CodingNinja package.

If you are using a Java code editor, then we can directly create a package using that code editor.

Accessing a package

We can access the package using three ways:-

  1. packageName.*
  2. packageName.className
  3. packageName

Lets discuss them in detail

  1. packageName.*: When we use this method, then all the class in that package gets imported to the current class. Refer to the code below.
package example
import CodingNinjas.*;

public class Main{
    public static void main(String args[]){  
        System.out.println("Hey..");
    }  
}
You can also try this code with Online Java Compiler
Run Code

In the above code, we can access all the classes of the CodingNinjas package.

2. packagedName.className: When we use this method then only a particular class of that package gets imported. Refer to the code below:

package example
import CodingNinjas.Main;

public class Main{
    public static void main(String args[]){  
        System.out.println("Hey..");
    }  
}
You can also try this code with Online Java Compiler
Run Code

In the above code, only the Main class of the CodingNinjas package gets imported.


3. packageName: If we use this method then all the declared classes of that package get imported. In this method, there is no need to write import because we can access its classes by using packageName.className. It is generally used when the two packages have classes with the same name. Refer to the code below:

package example

public class Main{
    public static void main(String args[]){  
        
        //Creating an object of the Main class of CodingNinjas package.
        CodingNinjas.Main obj = new CodingNinjas.Main();
    }  
}
You can also try this code with Online Java Compiler
Run Code

The order to write a program in java must be:-

Frequently Asked Questions

What is the difference between a package and a class in Java?

A package is a collection of related classes and interfaces, serving as a namespace to avoid naming conflicts, while a class is a blueprint for creating objects, defining their properties and methods. Packages organize code, whereas classes encapsulate data and behavior.

What are user-defined packages in Java?

User-defined packages are custom packages created by developers to group related classes and interfaces according to their application's requirements. They help in organizing code logically, enhancing maintainability, and avoiding naming conflicts with built-in packages.

How many packages are in Java?

Java has several built-in packages, including java.lang, java.util, java.io, java.net, java.sql, java.nio, java.time, java.math, and many more, covering various functionalities.

Conclusion

In this article, we thoroughly learned packages in Java, starting with their purpose and importance. We discussed the advantages they offer in organizing code, avoiding naming conflicts, and enhancing modularity. Additionally, we covered accessing packages, handling naming conflicts, and creating user-defined packages for better code management.

Recommended Readings:

Live masterclass