Package in Java: Types, Examples, and Usage Guide

Published: 22 Nov 2025 | Reading Time: 5 min read

Table of Contents

Key Takeaways From the Blog

Introduction

In Java a package is a blueprint method of class and interface combination which are closely related. Essentially it is used to organize coding, avoid naming conflicts and allow the code to be reused. Packages, by breaking down big programs into logical units, make the projects more understandable and easy to maintain, particularly in cases of complicated and expanding applications.

Java supports both built-in and user-defined packages, enabling developers to access prewritten functionality or create their own organized code modules. Understanding how packages work including their creation, compilation, directory structure, and usage is essential for writing modular, efficient, and well-structured Java programs suited for professional development.

What is a Package in Java?

A Java package is a namespace that holds a collection of related classes and interfaces. By using packages, developers can avoid naming conflicts and make code more maintainable. It also helps organize large codebases by placing classes logically according to their purpose.

Syntax to Create Java Package

package packageName;

By specifying a package at the beginning of a Java file, you assign that class or interface to the given package.

How to Declare a Java Package?

Below is the way to declare package in java example, the package keyword is at the beginning of the Java file, followed by the package name.

// Save as Simple.java
package mypack;

public class Simple {
    public static void main(String args[]) {
        System.out.println("Welcome to package");
    }
}

Compiling and Running Java Packages

To compile a Java package from the command line, you need to call the javac command and the -d flag used to indicate the directory where .class files will be placed.

To compile:

javac -d . Simple.java

The -d flag indicates where the compiled .class file is to be placed in the destination directory. The . refers to the current directory.

To run the program: Use the fully qualified name of the class:

java mypack.Simple

Naming Conventions and Structure

Java packages follow specific naming conventions and organizational structures to ensure clarity, avoid conflicts, and support maintainability in complex projects.

Package Naming Conventions

Packages need to be named with a hierarchical naming pattern that will generate unique namespaces. The Java community along with the Java Language Specification suggest that package names should start with reversed internet domain name of your organization (e.g. com.example for example.com). After that, any relevant subdomains or internal naming conventions that represent the project, module, or function can be used, like com.example.project.module.

By using this method the probability for two packages to have the same name thus causing the software to malfunction, is lowered substantially even if one decided to share his/her code with others or use third party libraries.

Naming Pattern Examples:

Structure in the File System

The directory or folder structure of your source files has to reflect the package hierarchy. Every dot (.) in the package name stands for a folder. Thus the package com.example.utils has to be located at the file path com/example/utils/. Such a correspondence enables the Java compiler and runtime to find classes in the classpath properly.

Unnamed Package

When there is no package declaration, the class is considered to be in the unnamed package. Using this is disfavored in professional or large-scale development, as classes in unnamed packages cannot be imported by classes in named packages, and it can cause problems with organization and making changes.

Quick Recap: Packages organize Java code, prevent naming conflicts, follow hierarchical naming, and require matching directory structure for correct compilation and execution.

Subpackages in Java

A subpackage is simply a package within another package. It enables you to encapsulate yet closer related classes and interfaces. The name of the subpackage usually adheres to the reverse domain name convention.

Example of Subpackages:

// Save as Simple.java in com/javatpoint/core
package com.javatpoint.core;

class Simple {
    public static void main(String[] args) {
        System.out.println("Hello subpackage");
    }
}

To compile:

javac -d . Simple.java

To run:

java com.javatpoint.core.Simple

Output:

Hello subpackage

Importing Packages and Classes

One can easily get hold of any class or interface from other packages in Java by using import statements in the source file. This mechanism is very helpful in code organization and ensures that the code is more modular and maintainable.

Import Statement Basics

If you want to use a class or an interface from a different package, you put an import statement in your source file at the top (right after the package declaration, if there is one). The two main forms are:

Class import:

import packageName.ClassName;

Example:

import java.util.ArrayList;

Interface import:

import packageName.InterfaceName;

Example:

import java.util.List;

Wildcard import: You can also import all public classes and interfaces from a package using the wildcard character (*):

import java.util.*;

This imports all public types from the java.util package but does not include types from any subpackage (e.g., java.util.concurrent is not included).

Some packages, like the java.lang package, are imported automatically in every Java program, so you don't need to explicitly import core classes such as String or System.

Accessing Classes Without Import

If you prefer not to use the import statement, you can access any class by its fully qualified name, for example:

java.awt.Frame frame = new java.awt.Frame();

This is especially useful when different packages contain classes with the same name (such as java.util.Date and java.sql.Date).

Static Import Statement

The static import statement allows you to access public static members (fields and methods) of a class directly, without qualifying them with the class name. This is useful for simplifying code that uses many static methods or constants.

Example:

import static java.lang.Math.*;

Now you can write sqrt(16) instead of Math.sqrt(16).

You can also import a single static member:

import static java.lang.Math.PI;

Importing from Subpackages

Remember, importing a package does not automatically import its subpackages. For example, import java.awt.*; imports all public classes in the java.awt package but not those in java.awt.event. To use classes from a subpackage, you must import them explicitly.

Quick Note: Use import statements for accessing external classes, rely on fully qualified names for conflicts, and apply static imports for cleaner syntax.

Using Package Members

After importing a package or class, you can access and use its classes, interfaces, and other members in your code. Java provides several ways to reference these members, each with implications for readability, maintainability, and access control.

Accessing Members by Simple Name or Fully Qualified Name

Access Control and Package Members

The ability to access classes or members from a package is determined by their access modifiers:

This means that, even if you import a class, you may not be able to access all of its members, depending on their access level.

Package Declaration and Sub-Packages

A package declaration at the top of a source file defines the package to which the class or interface belongs. Remember, importing a package does not import its sub-packages; you must import them explicitly if needed.

Classpath and Member Accessibility

The classpath determines where the Java compiler and runtime search for packages and classes. If a class or package is not on the classpath, it cannot be accessed, regardless of its access modifier.

Example: Dealing with Name Ambiguities

If two packages contain classes with the same name, such as java.util.Date and java.sql.Date, you must use the fully qualified name to specify which one to use:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date();

Key Takeaways:

Types of Java Packages

The types of packages in java broadly classified into two categories:

1. Built-in Packages

Java consists of numerous pre-implemented packages that contain a variety of functionalities. Pre-implemented packages consist of a huge number of helpful classes.

Key Packages in Java

Example 1: Using java.util Package

java.util is a widely define package in java. It offers a group of data structures such as ArrayList, HashMap, and Date.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<String>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        for(String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Explanation:

Output:

Apple
Banana
Cherry

Example 2: Using java.io Package

The java.io package handles input and output, which handles file reading and writing.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
            String line;
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch(IOException e) {
            System.out.println("Error reading file.");
        }
    }
}

Explanation:

Output:

Hello, World!
Welcome to Java Programming.

Example 3: Use of java.awt Package

The java.awt package is used in the development of graphical user interfaces (GUIs).

import java.awt.Button;
import java.awt.Frame;

public class Main {
    public static void main(String[] args) {
        Frame frame = new Frame("Simple AWT Example");
        Button button = new Button("Click Me");

        button.setBounds(50, 50, 80, 30);
        frame.add(button);

        frame.setSize(200, 200);
        frame.setLayout(null);
        frame.setVisible(true);
    }
}

Explanation:

Output:

(A window with a "Click Me" button appears)

Example 4: Using javax.swing Package

The javax.swing package provides more advanced GUI components than java.awt.

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Swing Example");
        JButton button = new JButton("Press Me");

        frame.add(button);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Explanation:

Output:

(A window with a "Press Me" button appears)

Bottom Line: Built-in packages cover utilities, I/O, networking, and GUI programming, offering prebuilt functionality to significantly speed up Java development.

2. User-defined Packages

Other than the built-in packages, Java also provides an option for the users to design user-defined packages for class grouping. User-defined packages enable the organization of significant applications.

How to Define a User-Defined Package?

To state a user-defined package:

Example

Save the file with MyPackage/MyClass.java:

package MyPackage;

public class MyClass {
    public void greet() {
        System.out.println("Hello from MyPackage!");
    }
}

Save the file name with Main.java:

import MyPackage.MyClass;

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        myClass.greet();
    }
}

Explanation:

Output:

Hello from MyPackage!

Key Takeaways:

Static Import in Java

Static import enables you to use static members (fields or methods) of a class as if they are global without any need to preface them with the class name. This is supported for Java 5.

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(sqrt(16)); // No need to use Math.sqrt()
    }
}

Output:

4.0

Explanation:

Handling Name Conflicts and Access Control

Packages in Java play a crucial role in both managing class name conflicts and controlling access to classes and their members. Here's how these mechanisms work together, using the most relevant terms:

Java uses packages to create unique namespaces. This means that classes with the same name can exist in different packages without class name collisions. For example, you might have java.util.Date and java.sql.Date in the same project. To specify exactly which class you want to use, you can reference it by its fully qualified name (e.g., java.util.Date date = new java.util.Date();). This approach avoids name conflicts and ensures clarity in large codebases.

Access control in Java is enforced through access modifiers (such as public, protected, and the default access modifier—when no modifier is specified). These modifiers determine how classes and their members can be accessed across package boundaries:

When designing user-defined packages, following package naming conventions (such as using all lowercase and reverse domain names) further reduces the risk of name conflicts with other packages, especially in large or collaborative projects.

Example:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();  // Use fully qualified name
        System.out.println(date);
    }
}

Explanation:

Output:

Mon Mar 24 17:45:30 UTC 2025

CLASSPATH and Directory Structure

Java uses a directory structure identical to that of the package hierarchy. For instance, a package mypackage will be equivalent to a directory mypackage/ with class files. The CLASSPATH environment variable refers to the root directory of the packages or classes so that Java can find them at runtime.

Loading Class Files or JAR Files

There are two methods through which class files or JAR files are loaded in Java: temporary and permanent.

Temporary Loading:

Permanent Loading:

Example

Save the file with Car.java:

package vehicles;

public class Car {
    public void display() {
        System.out.println("This is a Car.");
    }
}

Save the file with Bike.java:

package vehicles;

public class Bike {
    public void display() {
        System.out.println("This is a Bike.");
    }
}

Save the file with Main.java:

package vehicles;

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.display();  // Output: This is a Car.

        Bike bike = new Bike();
        bike.display();  // Output: This is a Bike.
    }
}

Explanation:

Output:

This is a Car.
This is a Bike.

Quick Recap: Classpath directs Java to locate compiled classes, enabling execution of packaged code from directories or JAR files.

Conclusion

In conclusion, package in Java is fundamental to structuring and storing code. By using the pre-supplied packages such as java.util, java.io, and java.awt in the standard Java distribution and user-specified packages, developers can enhance the code's modularity, reusability, and maintainability. It is required to know package structure, static import management, and name collision resolution to write clean and efficient Java code.

Why It Matters?

Packages are essential for building scalable, maintainable Java applications. They prevent naming conflicts, enhance modularity, and improve code organization—critical for team collaboration and large projects. By separating functionality into clear namespaces, packages support cleaner architecture, easier debugging, faster development, and long-term project sustainability.

Practical Advice for Learners

Frequently Asked Questions

What are the 2 types of Java packages?

Built-in Packages: Pre-defined packages in Java, made available through the Java API, containing handy classes and interfaces for frequent operations such as I/O, network manipulation, and data manipulation (e.g., java.util, java.io).

User-defined Packages: Packages developed by programmers to package their own classes. They provide code management and prevent naming clashes for large-scale applications (e.g., mypackage, com.example).

What are the 4 basic things in Java?

Classes: A class is a template or blueprint to construct objects and states, and it defines properties and methods. It is the Java coding construct to organize code.

Objects: An object is a class instance. It contains state (properties) and behavior (methods) and is utilized for modeling things from the real world.

Methods: A method is a set of instructions that define how a class or object will act. It is utilized for actions or calculations' needs.

Variables: Variables are used to hold data in the memory. Variables in Java hold various types of data, including integers, strings, or objects. Variables define the status of an object.

What are the any 5 packages in Java?

java.lang: Holds core classes such as String, Math, Object, and Thread. This package is implicitly imported into all Java programs and forms the core of the language.

java.util: Holds utility classes for data structures (i.e., ArrayList, HashMap), date/time manipulation (Date, Calendar), and random number generation (Random).

java.io: Holds classes for input/output (reading/writing files, File, BufferedReader, PrintWriter) and stream manipulation (InputStream, OutputStream).

java.net: Holds classes for communications and networking like Socket, URL, URLConnection, and InetAddress, enabling the Java programs to communicate through the internet.

javax.swing: Holds classes for GUI programming like JButton, JLabel, JFrame, and JPanel. It enables windowed applications to be created.

Can a Java package contain multiple public classes?

No. A Java file can have only one public class, and the public class must be named the same as the file. However, a package can contain several non-public classes.


Related Articles


Source: NxtWave - https://www.ccbp.in/blog/articles/package-in-java