Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconPackages in Java & How to Use Them?

Packages in Java & How to Use Them?

Last updated:
18th Apr, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Packages in Java & How to Use Them?

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.

Ads of upGrad blog

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.

Explore Our Software Development Free Courses

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.

Explore our Popular Software Engineering Courses

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.

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

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. 

Ads of upGrad blog

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!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What is a package and its types?

A package is a collection of related Java entities such as classes, subclasses, interfaces, annotations, and enumerations. It can also contain sub-packages. Packages in Java are of two types - built-in packages and user-defined packages.

2Why do we use packages in Java?

We use packages in Java to prevent naming conflicts, make searching, locating, and using classes, interfaces, annotations, and enumerations easier, control access, and data encapsulation.

3What is package-level access in Java?

Package level access in Java is the default access level provided by Java in case no access modifier is specified. The role of access modifiers is to restrict accessibility to a class, variable, or method to which it applies.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas &#038; Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions &#038; Answers For Freshers &#038; Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16879
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas &#038; Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling &#038; Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions &amp; Answers 2024 [For Freshers &amp; Experienced]
44560
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features &#038; Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas &#038; Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon