Published: 22 Nov 2025 | Reading Time: 5 min read
package packagename; which is located at the top of a file.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.
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.
package packageName;
By specifying a package at the beginning of a Java file, you assign that class or interface to the given 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");
}
}
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
Java packages follow specific naming conventions and organizational structures to ensure clarity, avoid conflicts, and support maintainability in complex projects.
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:
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.
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.
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
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.
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.
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).
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;
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.
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.
import java.util.ArrayList;), you can refer to the class by its simple name (ArrayList).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.
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.
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.
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:
The types of packages in java broadly classified into two categories:
Java consists of numerous pre-implemented packages that contain a variety of functionalities. Pre-implemented packages consist of a huge number of helpful classes.
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
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.
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)
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.
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.
To state a user-defined package:
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 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:
import static java.lang.Math.*; gives direct access to the Math class static methods.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
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.
There are two methods through which class files or JAR files are loaded in Java: temporary and permanent.
Temporary Loading:
Permanent Loading:
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.
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.
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.
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).
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.
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.
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.
Prime Number Program in Java: Explained with Examples - Learn how to write a prime number program in Java with clear logic, optimized algorithms, examples, and interview-ready explanations. (04 Jan 2026, 8 min read)
Why Encapsulation in Java Matters: Learn with Code Snippets - Understand encapsulation in Java, a key object-oriented principle used to restrict direct access and protect internal data from unauthorized changes. (04 Jan 2026, 5 min read)
Master Binary Search in Java: Fast and Efficient Searching Explained - Learn Binary Search in Java with clear logic, easy code examples, and real-world applications. Boost your coding skills with this step-by-step guide! (03 Jan 2026, 5 min read)
Learn Bubble Sort in Java: Easy Sorting Technique Explained - Get a complete guide on bubble sort in Java, including coding examples and tips to understand this basic but important sorting algorithm. (02 Jan 2026, 6 min read)
Best Java Training Institutes in Hyderabad: Your Guide to Career Success - Find the best Java training institutes in Hyderabad for hands-on learning, placement support, and industry-recognized certifications. (02 Jan 2026, 5 min read)
Understanding Inheritance in Java: Key Concepts & Benefits Explained - Learn all about inheritance in Java with clear examples. Understand types, benefits & how it supports code reusability in object-oriented programming. (02 Jan 2026, 8 min read)
Source: NxtWave - https://www.ccbp.in/blog/articles/package-in-java