View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Packages in Java & How to Use Them?

By Pavan Vadapalli

Updated on Nov 14, 2022 | 7 min read | 9.9k views

Share:

Packages in Java are used to group related classes, interfaces, and sub-packages. We use Java packages to avoid naming conflicts since there can be two classes with the same name in two different packages. Furthermore, searching, locating, and using interfaces, classes, annotations, and enumerations become easier with Java packages. 

Using the Java programming language to write software involves numerous individual classes, and it only makes sense to organise related classes and interfaces into packages. In a way, you can compare Java packages to the folders in a computer that we use to organise various files and keep our work clutter-free.

Check out our free courses to get an edge over the competition.

This guide will discuss the different types of packages in Java and how to use them.

Types of Packages in Java

Packages in Java are divided into categories based on whether the user defines them or not. The two kinds of Java packages are: 

  • Built-in packages
  • User-defined packages

1. Built-in packages

Predefined or built-in Java packages come along as part of the Java Development Kit (JDK) and consist of many predefined classes and interfaces that are part of Java APIs. Some of the commonly used built-in packages in Java are as follows:

  • java.io: Contains classes for supporting input/output operations.
  • java.lang: This in-built package is imported automatically and contains language support classes.
  • java.util: Contains utility classes for implementing data structures such as dictionary and support, linked list, date and time operations, etc.
  • java.net: Contains classes that support network operations.

Check out upGrad’s Advanced Certification in DevOps

We have to use the import statement to import any in-built Java packages and use the classes it contains. 

A simple example to show the use of the ArrayList class of Java.util package is as follows:

package Example;

import java.util.ArrayList;
class BuiltInPackage {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<>(3);
        myList.add(3);
        myList.add(2);
        myList.add(1);
        System.out.println(“The list has the elements: ” + myList);
    }
}

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

Output:

The list has the elements: [3, 2, 1]

In the above example of Java.util.ArrayList, Java is the top-level package, util is a sub-package, and ArrayList is a class present in the sub-package util.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Importing packages in Java

As shown in the earlier example, Java has an import statement that lets us import an entire package or use only certain interfaces and classes defined in the package.

The general syntax of the import statement is:

  • import package.name.ClassName; //Imports a certain class only
  • import package.name.* //Imports the whole package

For example, import java.util.Date; imports only the Date class whereas import java.io.*; imports everything the java.io package contains.

However, the import statement is optional in Java, and if we want to use the class or interface from a certain package, we can use its fully qualified name as follows:

class MyClass implements java.util.Date {
    //body
}

2. User-defined packages

As evident from the name, user-defined packages are created by the user for grouping classes, interfaces, and sub-packages. 

Creating a user-defined package

To create a user-defined package in Java, we will choose a name for our package and use the package command as the starting statement in the Java source file. As an example, we will create a package named ExamplePackage using the following statement:

package ExamplePackage;

The package statement specifies the package to which the classes we define will belong. If we do not use the package statement, the class names will be put into the default package in Java which has no name.

 Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Creating a class in the Java package 

Once we have created the package, the next step is to create a class inside the package. For this, we will declare the package name in the first statement of the program, followed by including the class as part of the package. 

Given below is a simple program to show how to create a class in a Java package. In the given an example, we create a class Calculate inside the package ExamplePackage.

package ExamplePackage;
public class Calculate {
   public int add(int p, int q){
return p+q;
   }
   public static void main(String args[]){
Calculate obj = new Calculate();
System.out.println(obj.add(70, 12));
   }
}

Output: 82

Java stores packages in file system directories. So, the above program will be saved in a file as Calculate.java and stored in the directory named ExamplePackage. When the file is compiled, Java will create a ‘.class’ file and store it in the ExamplePackage directory. 

Now, you can use the ExamplePackage package in another program. Here’s how:

import ExamplePackage.Calculate;
public class Demo{
   public static void main(String args[]){
Calculate obj = new Calculate();
System.out.println(obj.add(200, 523));
   }
}

Output: 723

In the above example, we have imported the package ExamplePackage to use the class Calculate. Importing the package as ExamplePackage.Calculate imports only the Calculate class. However, if you have more than one class inside the ExamplePackage package, you can use all the classes of the package by using the following import statement:

import ExamplePackage.*;

Creating a class inside a package while importing another package

To create a class inside a package while importing another package, we will begin by declaring the package name and then importing the other package. The following example demonstrates the same:

package OtherPackage; //Declaring a package
import ExamplePackage.Calculate; //importing a package
public class Example{
   public static void main(String args[]){
Calculate obj = new Calculate();
System.out.println(obj.add(300, 700));
   }
}

Output: 1000

In the above example, we declare the package OtherPackage, import the class Calculate from the package ExamplePackage, and then create the class Example.

Importing a class using a fully qualified name

We can avoid the import statement by using a fully qualified name. Using a fully qualified name makes only the declared class of the package accessible. But we need to use a fully qualified name every time we access the class or interface. Importing a class using a fully qualified name comes in handy when two packages have the same class name. 

The following example illustrates the same:

1. Calculate.java

package ExamplePackage;
public class Calculate {
   public int add(int x, int y){
return x+y;
   }
   public static void main(String args[]){
Calculate obj = new Calculate();
System.out.println(obj.add(20, 50));
   }
}

2. Demo.java

package OtherPackage; //Declaring a package
public class Demo{
   public static void main(String args[]){
ExamplePackage.Calculate obj = new ExamplePackage.Calculate(); //Using fully qualified name instead of import
System.out.println(obj.add(200, 100));
   }
}

Output: 300

In the example below, we have used the fully qualified name ExamplePackage.Calculate to create the object of it instead of importing the package. 

3. Sub-Packages in Java

Now that we have an idea about Java packages and how to create them let us understand the concept of sub-packages in Java.

A sub-package is a package inside another package and is used to categorise the package further. In other words, if we create a package multiply inside ExamplePackage package, then multiply is the sub-package. Thus, if we want to create a class within this sub-package multiply, then the sub-package should have a declaration at the start.

The following program demonstrates the concept of a Java sub-package:

package ExamplePackage.multiply; //Declaring the sub-package
public class Multiplication {
int product(int p, int q){
return p*q;
}
}

Now, if we want to use the Multiplication class, we can either: 

  1. Import it using the statement import ExamplePackage.multiply; or 
  2. use fully qualified name like ExamplePackage.multiply.Multiplication obj = new ExamplePackage.multiply.Multiplication();

Way Forward

Packages in Java can either be built-in packages or user-defined and are essential for better access and management of code. The concept of Java packages is crucial for anyone in the software development field. 

upGrad’s Job-linked PG Certification in Software Engineering is a 5-month online program that can help you master programming skills and prepare for software roles. The program focuses on pivotal skills such as Java, JavaScript, CSS3, HTML5, etc., and is specially designed for freshers who want to learn to program.

Program Highlights:

  • Specialisation in MERN/Cloud-Native
  • 500+ content hours
  • 50+ live sessions
  • 350+ hours of hands-on training
  • Five industry projects
  • 360-degree learning support
  • Networking with industry experts

Sign up today and learn from the best!

Frequently Asked Questions (FAQs)

1. What is a package and its types?

2. Why do we use packages in Java?

3. What is package-level access in Java?

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program