Key Takeaways From the Blog
- Packages are the Java feature that groups classes that are related and also are used to prevent naming conflicts.
- Creating a package is done through the line package packagename; which is located at the top of a file.
- There are several packages in Java, for instance, java.util, java.io, java.awt, javax.swing.
- Furthermore, you may write user-defined packages to have well-modularized and manageable code.
- Importing, static importing, and access control are the means by which classes in different packages can interact.
- Having the right directory structure and classpath setup is what makes it possible to execute Java code that is in packages.
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.
Here is the 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.
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. For instance:
- Top level domain name: com, org, net
- Reversed internet domain name: com.companyname
- Subdomains/internal naming: com.companyname.project.subproject
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.
Here is the subpackages program in java:
// 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;
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.
- 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
- If you use an import statement (e.g., import java.util.ArrayList;), you can refer to the class by its simple name (ArrayList).
- Without an import, or when name ambiguities exist (such as two classes with the same name in different packages), you must use the fully qualified name (e.g., java.util.Date).
Access Control and Package Members
The ability to access classes or members from a package is determined by their access modifiers:
- public modifier: The class or member is accessible from any package.
- protected access modifier: The member is accessible within its own package and by subclasses in other packages.
- default (package-private) access: If no modifier is specified, the class or member is accessible only within its own package.
- private modifier: The member is accessible only within its own class.
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 So Far
- Access levels determine visibility across package boundaries.
- Fully qualified names resolve ambiguity.
- Even with imports, accessibility depends on access modifiers.
- Subpackages are not automatically included from parent imports.
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
- java.util: The import util java contains utility classes for data structures (e.g., ArrayList, HashMap).
- java.io: Supplies input/output operation classes (e.g., BufferedReader, File).
- java.awt: Utilized to create graphical user interfaces (e.g., Button, Label).
- javax.swing: Contains classes for developing advanced GUIs (e.g., JButton, JFrame).
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
- The program utilizes the ArrayList class within the java util package.
- An ArrayList is defined and instantiated, and fruit names are inserted via the add() method.
- A loop is utilized to output every fruit within the list.
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
- The code is loading BufferedReader and FileReader from the java.io package.
- It is reading the file sample.txt using a BufferedReader.
- It is printing every line from the file to the console.
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
- The program is importing Button and Frame classes from java.awt package.
- An object of Button is created and added to the Frame.
- The frame is shown with the button on it.
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
- The class uses JButton and JFrame, which are accessed from the javax.swing package.
- JButton is created and placed inside a JFrame.
- The frame is made visible, and the button also becomes visible, where it remains.
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:
- Use the package keyword to state the package at the top of the Java file.
- Keep the Java file within a directory that reflects the package name.
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
- MyClass class is declared within a package named MyPackage.
- Main class imports the MyClass from MyPackage.
- An object of MyClass is created, and greet() function is invoked.
Output
Hello from MyPackage!
Key Takeaways So Far
- User-defined packages support modularity in custom applications.
- Directory structure must mirror package names.
- Public classes must match filenames.
- Multiple non-public classes can exist in a single file.
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
- The line import static java.lang.Math.*; gives direct access to the Math class static methods.
- Inside the main method, sqrt(16) is invoked directly to get the square root of 16 without using Math.sqrt(16).
- The 4.0, is output through System.out.println().
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:
- public members are accessible from any other class, regardless of package.
- protected members are accessible within the same package and by subclasses in other packages.
- package-private members (those with no explicit modifier, also called default access) are only accessible within their own package, providing access protection and encapsulation.
- private members are accessible only within the class they are declared in.
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.
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
- The code is importing all the classes from import java util *(like Date) and mypackage.MyClass, but there is a possibility of conflict if both packages contain a Date class.
- The code is using the fully qualified name java.util.Date to make sure that the Date class in the java.util package is being used without any ambiguity.
- The code instantiates a new Date object with the current date and time and prints it, which will print something like Mon Mar 24 17:45:30 UTC 2025.
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
- By providing the CLASSPATH in the command prompt.
- By providing the -classpath option while running the program.
Permanent Loading
- By providing the CLASSPATH in the environment variables of your system.
- By creating a JAR file of all the class files and putting the JAR file in the jre/lib/ext directory.
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
- Java has a single public class per.java file.
- Each public class resides in its own file, with filenames identical to the class names (Car.java for the class Car, Bike.java for the class Bike).
- The classes belong to the same package (vehicles).
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
- Always use lowercase, domain-based package naming.
- Keep directory structure aligned with package names.
- Prefer explicit imports for readability; avoid wildcard imports in large projects.
- Use static imports sparingly to maintain clarity.
- Practice with both built-in and user-defined packages for mastery.
Frequently Asked Questions
1. 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).
2. 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.
3. 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.
4. 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.