In this tutorial, we are going to discuss packages in Java with the help of example programs. In small projects, all the Java files usually have unique names. So, it is not difficult to put them in a single folder.
But, in the case of huge projects where the number of Java files is large, it becomes difficult to manage files in a single folder because the structure becomes disorganized.
Moreover, if different modules contain Java files with the same name, we cannot store them in the same folder due to naming conflicts. This problem can be overcome by using the concept of packages.
When developing a Java application, you should always create a proper package structure to improve code reusability, maintainability, and avoid naming conflicts. Now, let’s first understand what a package is.
What is Package in Java?
A package in Java is a namespace that groups related classes and interfaces together based on their functionality. It helps organize code in a structured and manageable way.
Although a package is a logical concept, it is mapped to a physical directory (folder) structure in the file system. Java provides many built-in packages, such as:
- java.lang
- java.util
- java.io
- java.net
These packages offer a well-organized and systematic way to categorize and manage Java classes and interfaces.
Realtime Example of Packages in Java
A real-life example of a package is similar to how we organize files on a computer. For instance, when you download movies, songs, or games, you usually create separate folders like this:
- Movies
- Songs
- Games
This helps keep files organized and easy to access.
In the same way, Java packages organize related classes and interfaces into separate groups. Another example is a library:
- A package is like a section of the library.
- Classes and interfaces are like books in the library.
- You can reuse these “books” whenever needed.
This reusability makes programming more efficient and easier to manage.
Why Packages are Important
When developing real-world Java applications, there may be hundreds or even thousands of classes and interfaces. They must be organized into a meaningful package name because packages help to:
- Organize code into meaningful groups.
- Avoid naming conflicts.
- Improve code reusability.
- Enhance maintainability.
- Support large-scale application development.
By using proper package names, you can easily reuse them in other programs and maintain a clean project structure.
Types of Packages in Java
Packages in Java can be broadly categorized into two types:
- User-defined packages
- Built-in packages (also called predefined packages)
Let’s first understand user-defined packages and how to create them in a Java program.
User-defined Package in Java
The package which is defined by the user or programmer is called user-defined package in Java. It is also called custom package in Java. It contains user-defined classes and interfaces organized according to specific functionality.
Creating a User-defined Package
Java provides a package keyword to create user-defined package. The general syntax to create a package in Java:
package packageName;
Here, packageName represents the name of the package. The package declaration must be the first statement in a Java source file (except comments), followed by class or interface definitions. For example:
package myPackage;
public class A {
// class body
}
In this example:
- myPackage is the name of a package.
- The statement “package myPackage;” indicates that the class “A” belongs to this package.
- The compiler will create a folder named mypackage (if it does not exist) when compiled using proper commands.
Naming Convention for User-defined Package in Real-Time Project
While developing a Java project, you should follow standard naming conventions for packages to ensure uniqueness, readability, and maintainability.
Look at the below a complete package structure of the project.
Reverse Domain Naming Convention
Java follows a widely accepted convention called reverse domain naming. Let’s understand it with examples.
Suppose you are working in IBM and the domain name of IBM is www.ibm.com. You can declare the package name by reversing the domain like this:
package com.ibm;
In this package name,
- com ➝ It is top-level domain of the company, and the folder starts with com.
- ibm ➝ It is the name of company where the product is developed. It is the sub-folder.
Extending the Package Structure
In real-world applications, packages are extended further based on project and functionality:
package com.ibm.hdfc.loan.homeloan;
In this extended package structure:
- hdfc ➝ It represents the client name for which you are developing our product or working on the project.
- loan ➝ It is the name of the project or application.
- homeloan ➝ It is the name of the modules of the loan project. There are a number of modules in the loan project like a home loan, car loan, or personal loan. Suppose you are working for the home loan module.
This is a complete packages structure, like a professional which is adopted in the company. Look at another example below:
package com.tcs.icici.loan.carloan.penalty;
In this package structure:
- Organization → tcs
- Client/project → icici
- Domain → loan
- Module → carloan
- Sub-feature → penalty
Best Practices to Create a Package
Follow these guidelines when creating packages in Java:
- Give a meaningful package names that clearly convey the purpose of the contained classes. It boosts code readability and maintainability.
- Organize classes based on their functionality, that makes it easier to find and work with related classes.
- Always try to avoid over nesting of packages, that can lead to confusion.
- Always keep a balance between hierarchy and simplicity.
- Follow Java naming conventions.
- Use the lowercase for package names and follow the reverse domain notation.
- Use proper access modifiers for classes within your package.
- Limit visibility to only what’s necessary for other classes.
How to Create Package in Eclipse IDE?
In Eclipse IDE, there are the following steps to create a package in Java. They are as:
1. Right-click on the ‘src’ folder as shown in the below screenshot.

2. Go to New option and then click on package.
3. A window dialog box will appear where you have to enter the package name according to the naming convention and click on Finish button. Once the package is created, a package folder will be created in your file system where you can create classes and interfaces.
Predefined Packages in Java (Built-in Packages)
Predefined packages in Java are those which are developed by the Sun Microsystem. They are also called built-in packages. These packages consist of a large number of predefined classes, interfaces, and methods that are used by the programmer to perform any task in his programs.
Java APIs contains the following predefined packages, as shown in the below figure:
Java Core Packages:
1. Java.lang: The ‘lang’ stands for language. The Java language package consists of Java classes and interfaces that form the core of the Java language and the JVM. It is a fundamental package that is useful for writing and executing all Java programs. Examples are classes, objects, string, thread, predefined data types, etc. It is imported automatically into the Java programs.
2. Java.io: The ‘io’ stands for input and output. It provides a set of I/O streams that are used to read and write data to files. A stream represents a flow of data from one place to another place.
3. Java util: The ‘util’ stands for utility. It contains a collection of useful utility classes and related interfaces that implement data structures like LinkedList, Dictionary, HashTable, stack, vector, calender, data utility, etc.
4. Java.net: The ‘net’ stands for network. It contains networking classes and interfaces for networking operations. The programming related to the client-server can be done by using this package.
Window Toolkit and Applet:
1. Java.awt: The ‘awt’ stands for abstract window toolkit. The Abstract window toolkit package contains GUI (Graphical User Interface) elements, such as buttons, lists, menus, and text areas. Programmers can develop programs with colorful screens, paintings, and images, etc using this package.
2. Java.awt.image: It contains classes and interfaces for creating images and colors.
3. Java.applet: It is used for creating applets. Applets are programs that are executed from the server into the client machine on a network.
4. Java.text: This package contains two important classes, such as DateFormat and NumberFormat. The class DateFormat is used to format dates and times. The NumberFormat is used to format numeric values.
5. Java.sql: SQL stands for the structured query language. This package is used in a Java program to connect databases like Oracle or Sybase and retrieve the data from them.
Java Package Development
Java provides a large number of predefined packages that contain classes and interfaces to support application development. These classes and interfaces provide various methods to perform different tasks.
For example, the Java language includes a package called java.lang, which contains classes such as String, StringBuffer, StringBuilder, all wrapper classes, and the Runnable interface. The String class provides many methods such as length(), toUpperCase(), and toLowerCase().
There is no fixed number of packages in Java. The JDK contains hundreds of packages, and they continue to evolve with each new version.
How to See List of Predefined Packages in Java?
Method 1: Using JDK Source Code (Recommended)
1. Go to your JDK installation folder. For example:
C:\Program Files\Java\jdk-17
2. Locate the file:
src.zip
3. Open (or extract) src.zip
4. Inside it, you will see folders like:
- java.lang
- java.util
- java.io
- java.net
- java.time
5. Open any package (e.g., java.lang) to view classes like:
- String
- StringBuilder
- Thread
Method 2: Using Official Documentation (Best Practice)
Visit the official Java API documentation:
- Browse all available packages and classes
- Always up-to-date with the latest Java version
Method 3: Using IDE (Easiest Way)
Use IDEs like:
- IntelliJ IDEA
- Eclipse
- VS Code
Follow these steps:
- Create a Java project
- Expand External Libraries / JDK
- View all packages like java.lang, java.util, etc.
Java Packages Example Program
Let us take a simple example program where we will create a user-defined package in a systematic manner.
Example 1:
// Declare package name by reversing domain name, project name 'java', and module name is core java.
package com.scientecheasy.java.corejava;
// Declare class name.
public class CreatePackage
{
public static void main(String[] args)
{
System.out.println("How to create a Java package");
}
}How to Compile a Package in Java?
If you are not using an IDE (like Eclipse or IntelliJ), you should use the command line. The basic syntax is:
javac -d . FileName.java
In this syntax:
- javac → Java compiler.
- -d → Specifies the destination directory and creates folder structure based on package name.
- . → current directory. It places the folder structure in the current working directory.
Compile:
javac -d.CreatePackage.java // Here, CreatePackage.java is the file name.
After the compilation, the folder structure will be created automatically:
com |---> scientecheasy |------> java |------> corejava |------> CreatePackage.class
How to Run Java Package Program?
To run the program, you must use the fully qualified class name. The fully qualified name means class name with a complete package structure. The syntax to run Java code is:
java packageName.classNameNow run the above Java code. To Run:
java com.scientecheasy.java.corejava.CreatePackage
Output:
How to create a Java package
How to Import Package in Java
There are three ways to use classes from another package in Java:
- import package.*;
- import package.ClassName;
- Using fully qualified name (without import)
Let’s understand one by one with the help of an example.
1. Using package.*
An import keyword is used to make classes and interfaces of another package accessible in the current program. If we use package.*, all accessible (public) classes and interfaces of that package can be used in the current class. It does not include sub-packages. Let’s understand this with a simple example program.
Example 2:
// Create a package.
package com.scientecheasy.calculate;
public class Sum
{
// Declare instance variables.
int a = 20;
int b = 30;
// Declare method.
public void cal()
{
int s = a + b;
System.out.println("Sum: " +s);
}
}
// Create another package.
package com.maths.calculator;
// Importing the entire package into the current package.
import com.scientecheasy.calculate.*;
class SumTest{
public static void main(String[] args)
{
// Create an object of class and call the method using reference variable s.
Sum s = new Sum();
s.cal();
}
}Output:
Sum: 50
2. Using packageName.ClassName
If you import packageName.className, you can only access the declared class of this package. Let’s understand it through an example program.
Suppose scientecheasy has information about the Dhanbad city and TCS needs this information. We will declare two modules: Dhanbad and TCS. TCS is using Dhanbad class, but both have different package names. Whenever you are using a class of another package, you must import the package first of all.
Example 3:
package com.scientecheasy.state.cityinfo;
public class Dhanbad
{
public void stateInfo()
{
System.out.println("Dhanbad is one of the major cities of Jharkhand");
}
public void cityInfo()
{
System.out.println("Dhanbad is the coal capital of India.");
}
}
// Declare complete package statement for TCS.
package com.tcs.state.requiredinfo;
// Import the package with class name.
import com.scientecheasy.state.cityinfo.dhanbad;
class Tcs {
public static void main(String[] args)
{
Dhanbad d = new Dhanbad();
d.stateinfo();
d.cityinfo();
}
}Output:
Dhanbad is the first major city of Jharkhand. Dhanbad city is called coal capital city of India.
3. Using Fully Qualified Name (No Import)
If you use the fully qualified name, there is no need to use an import statement. You can directly refer to the class using its complete package name. This approach is especially useful when two different packages contain classes with the same name, to avoid ambiguity.
Example 4:
package com.tcs.state.requiredinfo;
class Tcs {
public static void main(String[] args) {
com.scientecheasy.state.cityinfo.Dhanbad d =
new com.scientecheasy.state.cityinfo.Dhanbad();
d.stateInfo();
d.cityInfo();
}
}This approach will work only if:
- The class Dhanbad is declared public.
- The package structure is correctly compiled and available in the classpath.
Advantage of Using Packages in Java
1. Maintenance: Packages help in maintaining large projects efficiently. If a new developer joined a company, he can easily locate and understand the required classes due to a well-organized package structure.
2. Reusability: You can place the common classes and functionalities in a package, allowing them to be reused across multiple projects or modules.
3. Name conflict: Packages help to resolve the naming conflict between the classes with the same name. For example, two classes named Student can exist in different packages:
- stdpack1.Student
- stdpack2.Student
These are uniquely identified using their fully qualified names.
4. Better Organization: Packages organize related classes and interfaces into logical groups, making the project structure clean, readable, and easier to manage.
5. Access Protection (Encapsulation): Packages provide access control using access modifiers such as public, protected, and default (package-private). This allows you to restrict visibility and protect data by controlling which classes or members can be accessed outside the package.
Key Points to Remember About Java Package
- While importing another package, package declaration must be the first statement and followed by package import.
- A class can have only one package statement, but it can be more than one import package statement.
- import can be written multiple times after the package statement and before the class statement.
- You must declare the package with root folder name (no sub folder name) and the last file name must be class name with a semicolon.
- When you import, it does mean that memory is allocated. It just gives the path to reach the file.
- import com.scientecheasy.state.cityinfo.dhanbad; is always better than import com.scientecheasy.state.cityinfo.*;.







