What is a Package in Java?

What is a Package in Java?

26 May 2024
Beginner
67 Views
15 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Package in Java

Are you a Java enthusiast? Have you just begun learning Java? Have you come across packages in Java? Package in Java in simple words is a collection of similar classes, subclasses, ennumerations, annotations, and interfaces. In Java, every class is a part of some or the other package. You need to import the package for using any specific class.

In this Java tutorial, we'll have a detailed discussion regarding all the aspects of packages in Java. After going through this, you'll have a concept clarity of types of packages, their pros and cons, applications, etc. Let's begin.

Read More: Top 50 Java Interview Questions and Answers

Why Are They Used For?

There are some common uses of packages in Java:

  • Encapsulation: Packages hide implementation details and display only the necessary functionalities.
  • Code Reusability: You can create reusable components and use them anywhere in the application by importing them.
  • Modularity and Organization: Maintenance and search are easy as packages consist of all related classes and interfaces.
  • Namespace Management: Packages create unique namespaces for different classes and interfaces thus avoiding naming conflicts when classes with the same name appear in two or more packages. It helps reduce ambiguity in code.
  • Access Control: Java provides different access levels (private, protected, public, and package-private) to restrict access to classes and their members. protected and default members have package-level access control.
Read More: What is Java? A Beginner Guide to Java

How Do Packages Work?

There is a resemblance between packages and directories. They have a similar structure. Let us understand this with an example. Let's suppose we have a package whose name is office.employee.rollcall, then there are three directories, office, employee, and rollcall such that rollcall is present in employee and employee is present inside office. Here, the office is the package name, the employee is the subpackage name and rollcall is the class name. You can access the directory using the CLASSPATH variable.

  • Package naming conventions: The packages in Java are named in the reverse order of the domain name. e.g. scholarhat.com becomes com.scholarhat.
  • Adding a class to a Package: For this, you need to add the package name at the beginning of the program and save it in the corresponding directory. To define a public class, we need a new Java file. Otherwise, we can add the new class to an existing .java file and recompile it.
  • Subpackages: These are packages defined inside another package. You cannot import them explicitly; they have no default access controls. They are like separate entities or package.

Accessing Classes inside a Package


// Importing the Random class from the java.util package
import java.util.Random;

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

// Importing all classes and interfaces from a specific package
import mypackage.*;

// Importing only a specific class from a package
import mypackage.MyClass;

// Using fully qualified names to avoid naming conflicts
import java.util.HashMap;
import mypackage.HashMap;

Example

  
       import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack stack = new Stack<>();  
  
        // Push elements onto the stack  
        stack.push(100);  
        stack.push(200);  
        stack.push(300);  
  
        // Print the top element of the stack  
        System.out.println("Top element:"+stack.peek());  
  
        // Pop elements from the stack  
        int poppedElement=stack.pop();  
        System.out.println("Popped element:"+poppedElement);  
  
        // Check if the stack is empty  
        System.out.println("Is the stack empty? "+stack.isEmpty());  
  
        // Get the size of the stack  
        System.out.println("Stack size:"+stack.size());  
  
        System.out.println("Stack elements:");  
        for (Integer element:stack)   
        {  
            System.out.println(element);  
        }  
    }  
}     

Output

Top element:300
Popped element:300
Is the stack empty? false
Stack size:2
Stack elements:
100
200    
Read More: Top 50 Java Full Stack Developer Interview Questions and Answers

Types of Packages in Java

Types of Packages in Java

1. Built-in packages

The classes in these packages are part of the Java API. These packages get installed when you install Java on your computer. The JAVA API is the library of pre-defined classes available in the Java Development Environment. Following are some of the built-in packages in Java

  • Java.lang: package of fundamental classes
  • Java.io: package of input and output function classes
  • Java.awt: package of abstract window toolkit classes
  • Java.swing: package of windows application GUI toolkit classes
  • Java.net: package of network infrastructure classes
  • Java.util: package of collection framework classes
  • Java.applet: package of creating applet classes
  • Java.sql: package of related data processing classes

The built-in packages are further classified into extension packages. These extension packages start with javax. For example:

  • Javax.swing
  • Javax.servlet
  • Javax.sql

The only default package without an explicit import statement is the java.lang package.

Built-in packages


public class Main {
    public static void main(String[] args) {
        // Using String (java.lang.String)
        String message = "Hello, World!";
        System.out.println(message);

        // Using Math (java.lang.Math)
        int max = Math.max(10, 20);
        System.out.println("Max: " + max);

        // Using System (java.lang.System)
        long currentTime = System.currentTimeMillis();
        System.out.println("Current Time: " + currentTime);
    }
}

Output

Hello, World!
Max: 20
Current Time: 1716034810123

In the above code, we implicitly import java.lang.* to have access to some of the fundamental classes provided by Java, such as Math, String, and System.

2. User-defined packages

As the name suggests, these packages are created by the developers to define the classes and interfaces as per the application requirements.

Syntax to create user-defined packages


package packageName;

The package keyword is used to define the package name. Declare the package before any import statements in the Java class. In your created package, ensure that all the classes should be public so that one can access them outside the package.

User-defined packages

Read More:

package package_first;

public class FirstClass {
    public void printFunctionFirst()
    {
        System.out.println("Hello this is our first package");
    }
}

package package_second;

public class SecondClass {
    public void printFunctionSecond()
    {
        System.out.println("Hello this is our second package");
    }
}

import package_first.FirstClass;
import package_second.SecondClass;

public class Testing {
    public static void main(String[] args)
    {
        FirstClass a = new FirstClass();
        SecondClass b = new SecondClass();
        a.printFunctionFirst();
        b.printFunctionSecond();
    }
}

Output

Hello this is our first package
Hello this is our second package

Using Static Import

This feature is included in the Java Version 5 and above. Using static import, one can use the static fields and methods defined in a class as public static without specifying the class in which the field is defined.


import static java.lang.System.*;

class StaticImportExample {
    public static void main(String args[])
    {
        // out without System prefix
        out.println("Welcome to ScholarHat");
    }
}

Output

Welcome to ScholarHat

Subpackage in java

A subpackage is a package inside another package. It improvises the package structure. You can use it to create related classes, group them, and make them a part of the bigger package. Let's take an example and understand.

Suppose, there's a package called Vehicles. Now you want to create some classes related to a specific type of vehicle, let's say bikes. In this case, you can create a subpackage named Bikes inside the major package, Vehicles. This organizes your package structure like files in the directory.

In the above image, one can look, at how the package structure is organized. The more the complexity of the application grows, the more organized must be the package structure.

Example of Subpackage

  • Create a utility class in the com.example.util subpackage.
    
    package com.example.util;
    
    public class Utility {
        public static void printMessage(String message) {
            System.out.println(message);
        }
    }
    
  • Create the main class in the com.example.main package and use the Utility class from the com.example.util subpackage.
    
    package com.example.main;
    
    import com.example.util.Utility;
    
    public class Main {
        public static void main(String[] args) {
            String message = "Hello from subpackage example!";
            Utility.printMessage(message);
        }
    }
    

To compile and run this code,

  • Navigate to the src directory
    
    cd src
    
  • Compile the Java files
    
    javac com/example/util/Utility.java com/example/main/Main.java
    
  • Run the Main class
    
    java com.example.main.Main
    
Read More:
Summary

We saw the importance of packages in Java. The two types of Java packages provide users with a lot of functionalities to develop their applications. The classes inside the packages make Java such an application-oriented programming language. It's widely used in all kinds of industries due to these features. For a practical understanding, consider our Java Programming Course.

FAQs

Q1. What is a package in Java?

Package in Java is a collection of similar classes, subclasses, enumerations, annotations, and interfaces.

Q2. What is package and its types?

Package in Java is a collection of similar classes, subclasses, enumerations, annotations, and interfaces. There are two types of packages in Java:
  1. Built-in packages
  2. User-defined packages

Q3. What is the difference between a library and a package in Java?

 In Java, a library is a collection of precompiled classes and methods that provide reusable functionality, while a package is a namespace that organizes related classes and interfaces, helping to avoid name conflicts and control access. 

Q4. How to write package name in Java?

In Java, package names follow these guidelines:
  • Use lowercase letters only.
  • Separate words with periods (.).
  • Traditionally, they follow a reverse domain name structure (e.g., com.example.mypackage).
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 16 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this