How to Create a Package in Java?

Java package is a collection of similar classes, sub-packages, interfaces, enumerations, and annotations.

We have folders in our computer to organize similar types of files; similarly, packages act like folders to organize the related classes, interfaces, and sub-packages. Thus making it easy to locate the classes and interfaces easily.

A Java software can contain several classes and interfaces for different purposes. Using the packages helps the programmer to categorize them quickly.

Java has two types of packages built-in package and a user-defined package. Some of the packages we usually use are java.lang, java.util,,, javax.swing, java.sql, etc. In this section, we will understand how to create and use the basic user-defined packages in Java.

Purpose of Package

  • Prevent the naming conflicts:

Packages facilitate the task of identifying a class uniquely. Thus, it is possible to have two classes of the same name in two different packages.

university.comp.Student and university.mech.Student.

  • Reusability of code:

The classes of one package reused into another package using the keyword import.

  • Access protection:

We can control the access to the classes and interfaces using access specifiers such as protected, default, and private.

  • Data encapsulation:

The classes which are for the internal purpose can be hidden from the programs.

  • Facilitates organization:

Categorizing the classes and interfaces makes it easier for the user to locate and maintain them.

Note: The interfaces and classes with the same name cannot be located in the same package. However, they must be placed in different packages. This is done by assigning different namespaces to each package in Java.

Types of Package in Java

Java packages are of two types

  1. Built-in packages