• Articles

Packages in Java: Types, Examples, and Working

Packages in Java: Types, Examples, and Working

Table of content

Show More

Packages are an important part of every program in Java. In this blog, we will explore every aspect of Java packages, including what they are, how they work, and how to create them. Moreover, you will also see the benefits of packages and the directory structure of packages.

Watch this Java video by Intellipaat:

Video Thumbnail

What are Packages in Java?

The packages in Java are groups of similar types of classes and interfaces. These serve as both a naming convention and a visibility control mechanism. Packages encapsulate classes and restrict access to these classes from external code, minimizing the chances of naming conflicts. Additionally, packages enable you to define class members that are visible only within the same package. This selective visibility enables the classes to gain knowledge of each other without exposing that internal information to the broader programming community. In the file system, packages are represented by directories, each of which corresponds to a package name.

Types of Packages in Java

Types of Packages in Java

There are two types of packages in Java:

  • In-built packages
  • User-defined packages

In-Built Packages: The Java Development Kit (JDK) includes predefined sets of packages that are known as built-in or standard packages. A number of classes from the Java API are included in these packages. These packages cover many different areas of programming, from simple input/output operations to more complex features like networking, GUI creation, and data structures. The built-in packages are stored in Java ARchive (JAR) files, which we can easily view when we unzip them, for example, lang, io, util, SQL, etc.

Some commonly used in-built packages in Java include:

  • java.lang: This package is automatically imported into every Java program. It contains basic classes such as Object and String, and basic data types like Integer and Boolean.
  • java.util: This package provides utility classes and data structures like ArrayList, HashMap, and Date.
  • java.io: This package supports input and output operations, including classes for file handling, streams, and readers/writers.
  • java.net: This package is used for networking tasks, including classes for working with URLs, sockets, and protocols.
  • java.awt and javax.swing: These packages are related to Abstract Window Toolkit (AWT) and Swing, providing classes for creating graphical user interfaces (GUIs).
  • java.sql: This package contains classes and interfaces for database connectivity, supporting Java Database Connectivity (JDBC).
  • java.math: This package includes classes for mathematical operations and working with arbitrary-precision arithmetic.
  • java.time: Introduced in Java 8, this package deals with date and time handling, offering improved functionality over the older java.util.Date and java.util.Calendar classes.
  • java.applet: Contains classes that are used for creating applets in Java.

User-Defined Packages: Java allows developers or users to create their own packages; these are called user-defined packages. They can be used in the same way as built-in packages and imported into other classes. However, if we remove the package statement, the class names are added to the nameless default package.

Go for this in-depth job-oriented Java Training Course now!

Get 100% Hike!

Master Most in Demand Skills Now!

How Do Packages Work in Java?

Following are the steps to create a package:

Naming the Package: For the sake of readability and code organization, consistent package naming conventions must be followed. To keep things consistent, package names should start with the reversed version of a unique domain name, like “com.example.” The package’s purpose should be enumerated in meaningful, multiword names, with additional components representing the project’s organization. Instead of using Java keywords, acronyms, and abbreviations, developers should use concise yet descriptive package names. 

Adding the Class into the Package: Next, we would add the package in a class. For this, we include the package declaration at the top of the Java class file. For example:

// MyClass.java
package com.example.myproject;
public class MyClass {
    // Class code here
}

In this example, the package statement comes before the class declaration, specifying that “MyClass” belongs to the “com.example.myproject” package. 

Accessing the classes present in a package: To access the class that belongs to a package, consider the following statements:

In the statement given below, the Vector class from the util package is imported:

// Import the ArrayList class from the util package.
import java.util.ArrayList;

In the second statement, we use “ * ” which means that all classes from the util package are imported, i.e.,

// Import all classes from the util package.
import java.util.*;

These import statements show how to access specific classes or all classes within a package in Java.

New to Java? Check out this blog on Fundamentals of Java to get started.

Creating a User-Defined Package in Java

Consider an example where we want to create a package named “geometry” containing classes for basic geometric shapes such as circles and rectangles. For this, you should follow the steps given below:

1. Choose a Meaningful Package Name:

Select a package name that reflects the domain of your classes. For this example, we’ll use “geometry.”

   // Example package declaration
   package com.example.geometry;

2. Include the Package Declaration:

In each Java source file belonging to the package, include the package declaration. If our chosen package name is “com.example.geometry,” the declaration should be:

package com.example.geometry;

3. Organize Source Files in a Directory Structure:

Arrange Java source files within a directory structure that mirrors the package hierarchy. For instance:

/path/to/your/project which refers to com/example/geometry/Circle.java

The directory is identified at the root level as “project.” Under this main directory, a hierarchical structure is revealed, beginning with a subdirectory named “com.” An additional division appears in the “com” directory when the “example” subdirectory is made. 

The “geometry” subdirectory forms a more detailed structure embedded within “example”. Finally, the result of this configuration is contained in the innermost directory called “geometry,” which contains the Java source file called “Circle.java.” This methodical arrangement establishes a distinct and modular structure for the related Java classes, mirroring the package hierarchy.

Now we will export this package into a class named ”Circle”. This is shown in the given code: 

package com.example.geometry;
public class Circle {
    private double radius;
    public Circle(double radius) {
        this.radius = radius;
    }
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

By organizing this class into the “geometry” package, you create a modular and maintainable structure for handling geometric shapes in your Java project. Other parts of your program can then import and utilize these classes as needed. Now, let’s say you have another Java class, i.e.MainClass, which is in a different directory. You want to import and use the Circle class from the “geometry” package:

// File: /path/to/your/other/directory/MainClass.java
import com.example.geometry.Circle;
public class MainClass {
    public static void main(String[] args) {
        Circle myCircle = new Circle(5.0);
        double area = myCircle.calculateArea();
        System.out.println("Area of the circle: " + area);
    }
}

In this example, the import com.example.geometry.Circle; statement allows you to use the Circle class from the “geometry” package in your MainClass file, even though it’s in a different directory. This is possible because the package hierarchy is specified in the import statement.

Learn more about Java Certification from this insightful Java Certification blog! 

How To Import Packages in Java

In Java, importing packages is a way to make classes and interfaces from other packages accessible to your current code file. Here’s how you can import packages in Java:

  • Single Class Import: If you want to import a specific class from a package, you use the import statement followed by the package name and the class name. For example:
import java.util.ArrayList;
  • Whole Package Import: If you want to import all the classes and interfaces from a particular package, you use the import statement followed by the package name and an asterisk *. For example:
import java.util.*;
  • Static Import: If you want to import static members (fields and methods) so that you can use them without class reference, you use the import static statement. For example:
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

These statements import the PI constant and the sqrt method from the Math class in the java.lang package so that you can use them directly in your code as PI and sqrt() without the Math class prefix.

Remember, the import statements must be placed between the package statement (if there is one) and the class definition in your Java file, typically at the top of the file.

Here’s an example of a Java class with import packages statements:

package com.example.myapp;

import java.util.List;
import java.util.ArrayList;
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

public class ExampleClass {
    public void useImportedClasses() {
        List<String> list = new ArrayList<>();
        double radius = 5.0;
        double area = PI * radius * radius;
        double length = sqrt(area);
    }
}

Prepare for the next interview with these Hibernate Interview Questions.

Access Protection in Packages

Packages introduce an additional layer of access control in Java, offering an advanced approach to managing the visibility of variables and methods within classes, subclasses, and across packages. Both classes and packages serve as mechanisms for encapsulating and defining the namespace and scope of variables and methods. While packages serve as containers for classes and subsidiary packages, classes operate as containers for both data and code, representing Java’s smallest unit of abstraction. This interaction between classes and packages gives rise to four categories of visibility for class members:

  1. Subclasses in the Same Package
  2. Non-subclasses in the Same Package
  3. Subclasses in Different Packages
  4. Classes That Are Neither in the Same Package Nor Subclasses

To navigate these categories effectively, Java employs three access modifiers—private, public, and protected. You can access anything made public from anywhere. Anything that is marked as private is only visible to members of that class. A member is visible to other classes in the same package and to subclasses if it does not have an explicit access specification. This is default access. An element is declared protected if you wish to make it visible to classes that directly subclass your class but not to anyone else outside of your current package.

Want to ace your next Java interview? Check out our recent blog post about the most common Java interview questions and answers!

The Directory Structure of Packages in Java

Suppose we have a package named “com.example.utilities.logger.” In this case, three directories will be created: “com,” “example,” and “utilities,” with “logger” residing within the “utilities” directory. The variable `PROJECT_PATH` will include the path to the parent directory, which is “com.” This setup ensures that classes are easily located, with a structured hierarchy reflecting the package naming convention. The `PROJECT_PATH` inclusion of the parent directory simplifies the retrieval of classes for effective and organized development.

To create the package structure described (`com.example.utilities.logger`), you can follow these steps:

1. Create the Project Directory:

Create a directory for your project. This will be the root directory containing your package structure.

mkdir PROJECT_PATH
cd PROJECT_PATH

2. Create Subdirectories: Create the necessary subdirectories to match the package structure.

mkdir -p com/example/utilities/logger

This command with the `-p` option creates parent directories as needed.

3. Navigate to the Package Directory: Navigate to the directory where your package resides.

cd com/example/utilities/logger

4. Create the Java Class: Create the `LoggerClass.java` file within the “logger” directory.

touch LoggerClass.java

5. Edit the Java Class: Edit the `LoggerClass.java` file and add the appropriate package declaration and class code.

// LoggerClass.java
  package com.example.utilities.logger;
   public class LoggerClass {
       public void logMessage(String message) {
           System.out.println(message);
       }
   }

The package structure with “LoggerClass” is successfully created in the correct directory. You can proceed to create another Java class in a different directory (not necessarily inside the package) and import and use “LoggerClass” .

Benefits of Packages in Java

Some of the benefits of the packages are listed below: 

Preventing Naming Conflicts: As already discussed previously, packages prevent naming conflicts. For example, consider the scenario where two classes share the name “Employee” but reside in different packages, such as “college.staff.cse. Employee” and “college.staff.ee.Employee.” If these two classes were not present in the different packages, this would have raised a naming conflict.

Improving Searchability and Usability: Packages make it easier to find and use enumerations, classes, interfaces, and annotations. Code component management and retrieval are made easier by this organization, which improves the efficiency of the development process as a whole.

Enabling Controlled Access: Access control is facilitated through the use of access specifiers. For instance, the “protected” and default (package-private) access levels restrict visibility. A protected member is accessible by classes in the same package and its subclasses, while a default member is visible solely to classes within the same package.

Facilitating Data Encapsulation: Packages contribute to data encapsulation or data hiding, emphasizing the encapsulation of code components within distinct packages. This encapsulation promotes a modular and organized structure, reinforcing the principles of object-oriented design.

Learn Java from scratch with this free Java Tutorial!

Key-Takeaways

We have seen in this blog what packages are in Java and how they work. Undoubtedly, the Java package stands as one of the most important elements for Java programmers. It not only enhances the coding style of developers but also minimizes the need for extensive additional work. Using packages in Java significantly contributes to improved code organization, making it an important tool for enhancing efficiency and streamlining the development process.

Course Schedule

Name Date Details
Python Course 23 Nov 2024(Sat-Sun) Weekend Batch View Details
30 Nov 2024(Sat-Sun) Weekend Batch
07 Dec 2024(Sat-Sun) Weekend Batch