Table of contents
1.
Introduction
2.
How Packages Work in Java
3.
Types of Packages in Java
3.1.
Built-in Packages in Java
3.2.
User-defined Packages in Java
4.
Using Static Import
5.
Handling name conflicts
6.
Directory structure
7.
Subpackage in Java
8.
Advantages of packages
9.
Accessing a package
10.
Frequently Asked Questions
10.1.
What is the difference between package and interface?
10.2.
What is the difference between a package and a class in Java?
10.3.
What are user-defined packages in Java?
10.4.
Why are packages important in Java?
10.5.
How do packages help in avoiding naming conflicts?
11.
Conclusion
Last Updated: Oct 7, 2024
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 as folders in the directory. They are used to store the classes, interfaces, and sub-packages of similar types. They are the main part of the encapsulation process as they help in encapsulating the data of the same type.

 Packages in Java

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: 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.


Also see, Duck Number in Java and Hashcode Method in Java.

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 below code.
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 below code:

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 below code:

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:-

Also see, Swap Function in Java

Frequently Asked Questions

What is the difference between package and interface?

A package is a namespace that organizes classes and interfaces, while an interface is a reference type that defines a contract of methods without implementation. Packages group related code, whereas interfaces allow classes to implement shared behaviors.

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.

Why are packages important in Java?

Packages are crucial in Java as they promote code organization, modularity, and reusability. They enable developers to group related classes and interfaces, improving maintainability and readability while preventing naming conflicts and providing access control through visibility modifiers.

How do packages help in avoiding naming conflicts?

Packages help avoid naming conflicts by providing a namespace for classes and interfaces. When two classes have the same name, placing them in different packages allows developers to differentiate them by using their fully qualified names, thus eliminating ambiguity.

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.

If you want to learn more about Java and want to practice some questions which require you to take your basic knowledge on Java a notch higher, then you can visit our Guided Path for Java

Live masterclass