Introduction to Java Packages
Course: Core Java Training
Topic: Introduction to Java Packages
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Java Packages
A package in Java is a mechanism used to organize related classes, interfaces, enumerations, and annotations into a logical group. Packages help developers structure large applications, avoid naming conflicts, control access to classes and members, and make code easier to maintain.
For example, a banking application may contain separate packages for customer information, account management, transactions, and reporting. Each package groups related functionality, making the project easier to understand and develop.
Java provides built-in packages such as java.lang, java.util, java.io, and java.time. Developers can also create their own packages to organize application-specific classes.
2. Learning Objectives
After completing this topic, you will be able to:
- Define Java packages and explain their purpose.
- Understand built-in and user-defined packages.
- Create packages using the
package keyword.
- Import classes and packages using the
import keyword.
- Use fully qualified class names.
- Understand package naming conventions and directory structures.
- Learn how packages interact with Java access modifiers.
- Compile and execute Java programs that use packages.
- Identify common package-related errors and their solutions.
3. What Is a Package in Java?
A package is a namespace that groups related Java types under a common name. Every Java class belongs to a package. If a source file does not declare a package, its types belong to an unnamed or default package.
Packages provide a structured way to manage application code and distinguish between classes that have the same simple name.
Example
Suppose two developers create a class named Employee. One class represents employees in a sales system, while the other represents employees in a payroll system.
com.company.sales.Employee
com.company.payroll.Employee
Although both classes are named Employee, their fully qualified names are different. Java can distinguish between them by using their package names.
4. Why Are Packages Important?
Packages play an important role in designing maintainable Java applications.
4.1 Code Organization
Packages group related classes together. For example, classes related to database operations can be stored in a database package, while classes related to user interfaces can be stored in a ui package.
4.2 Avoiding Naming Conflicts
Different packages can contain classes with the same simple name. Their fully qualified names distinguish them.
4.3 Access Control
Package boundaries work with Java access modifiers. Package-private members are accessible within the same package, while public types can be accessed from other packages when their visibility and other access requirements permit.
4.4 Code Reusability
Public classes and interfaces can be reused by other parts of an application or by other applications when they are available on the appropriate classpath or module path.
4.5 Easier Maintenance
A well-organized package structure makes it easier to locate classes, understand dependencies, test components, and maintain larger projects.
5. Types of Packages in Java
Java packages are commonly discussed in two categories: built-in packages and user-defined packages.
| Type |
Description |
Examples |
| Built-in Packages |
Packages provided by the Java platform and its APIs. |
java.lang, java.util, java.io |
| User-Defined Packages |
Packages created by developers to organize application code. |
com.example.student, com.company.billing |
6. Built-in Packages in Java
Built-in packages provide ready-to-use classes and interfaces for common programming tasks. They reduce the need to implement standard functionality from scratch.
| Package |
Purpose |
Example Classes |
java.lang |
Fundamental language classes and utilities. |
String, Math, System, Object |
java.util |
Collections, utilities, and general-purpose data structures. |
ArrayList, HashMap, Scanner |
java.io |
Traditional input and output operations. |
File, FileReader, BufferedReader |
java.time |
Date and time handling. |
LocalDate, LocalTime, LocalDateTime |
java.net |
Networking functionality. |
URL, URI, Socket |
java.sql |
Database access through JDBC. |
Connection, ResultSet, PreparedStatement |
Example: Using a Built-in Package
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Rahul");
names.add("Priya");
names.add("Amit");
System.out.println(names);
}
}
Output
[Rahul, Priya, Amit]
Explanation: The statement import java.util.ArrayList; makes the ArrayList type available by its simple name. The program uses this collection to store and display multiple strings.
7. The package Keyword
The package keyword declares the package to which a top-level type in a Java source file belongs. For a named package, the declaration must appear before import declarations and type declarations, apart from any permitted annotations or comments.
Syntax
package packageName;
Example
package com.example.student;
public class Student {
public void display() {
System.out.println("Student package example");
}
}
In this example, the Student class belongs to the com.example.student package.
8. Creating a User-Defined Package
A user-defined package is created by declaring a package name at the beginning of the Java source file and placing the source file in a matching directory structure when using a conventional filesystem-based project.
Step 1: Create the Package Class
Create a file named Calculator.java with the following code.
package mypackage;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
Step 2: Understand the Directory Structure
The source file should be placed in a directory named mypackage relative to the source root.
JavaProject/
mypackage/
Calculator.java
Main.java
Step 3: Create a Class That Uses the Package
Create a file named Main.java in the source root.
import mypackage.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(10, 5));
System.out.println(calculator.subtract(10, 5));
}
}
Output
15
5
Explanation: The Calculator class belongs to the mypackage package. The Main class imports it and calls its public methods.
9. The import Keyword
The import keyword allows a Java source file to refer to accessible types from other packages by their simple names. It helps make code shorter and easier to read.
Without an import, a class in another package can still be referenced by its fully qualified name.
9.1 Importing a Single Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
scanner.close();
}
}
The statement import java.util.Scanner; imports the Scanner type specifically.
9.2 Importing Multiple Classes
Multiple classes can be imported by using separate import statements.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
9.3 Importing All Accessible Types From a Package
A wildcard import uses an asterisk to make accessible types declared directly in the specified package available by their simple names.
import java.util.*;
This does not import subpackages. For example, import java.util.*; does not import types from java.util.concurrent.
9.4 Using a Fully Qualified Class Name
A fully qualified class name includes the package name and the type name. This approach can be useful when two packages contain types with the same simple name.
public class Main {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate =
java.sql.Date.valueOf("2026-10-23");
System.out.println(utilDate);
System.out.println(sqlDate);
}
}
Both classes are named Date, but their fully qualified names distinguish them. The java.sql.Date example uses a date-only value, while java.util.Date represents an instant in time.
10. Understanding the Default Package
If a Java source file does not contain a package declaration, its types belong to an unnamed package, often called the default package.
Example
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java Packages");
}
}
This class does not declare a package, so it belongs to an unnamed package.
The default package can be convenient for small experiments and beginner exercises. For larger applications, named packages are generally preferable because they provide better organization and enable normal package-based access control.
Important: Types in a named package cannot import types from an unnamed package. Avoid relying on the default package in production projects.
11. Package Naming Conventions
Java package names should be meaningful, consistent, and easy to understand. Common conventions include:
- Use lowercase letters for package names.
- Use periods to separate package-name components.
- Use descriptive names based on application functionality.
- Use a reversed organizational domain as the starting point when appropriate.
- Avoid Java keywords and invalid identifier characters.
- Keep package names consistent with the project's directory structure.
Examples
com.company.employee
com.company.payroll
org.example.inventory
in.justacademy.training
For example, a company with the domain company.com might use com.company as its package-name prefix.
12. Package Structure and Subpackages
Large Java applications are often divided into packages and subpackages to separate responsibilities.
Example Project Structure
com/
company/
app/
Main.java
model/
Employee.java
service/
EmployeeService.java
repository/
EmployeeRepository.java
This structure separates the main application, data models, business logic, and data-access operations.
Important: Java package names may look hierarchical, but a subpackage is a separate package. For example, com.company.model is not automatically part of the package com.company for access-control or import purposes.
13. Access Modifiers and Packages
Access modifiers determine whether classes, fields, constructors, and methods can be accessed from within the same class, the same package, subclasses, or unrelated classes.
| Modifier |
Same Class |
Same Package |
Subclass in Another Package |
Unrelated Class in Another Package |
public |
Yes |
Yes |
Yes, if other access requirements are satisfied |
Yes, if the declaring type is accessible |
protected |
Yes |
Yes |
Yes, subject to subclass access rules |
No |
| Package-private (no modifier) |
Yes |
Yes |
No direct access across packages |
No |
private |
Yes |
No direct access |
No direct access |
No direct access |
Top-level classes can generally be declared public or package-private. The private and protected modifiers are not permitted for ordinary top-level class declarations.
Example
package com.example;
public class Student {
public String name = "Aman";
private int age = 20;
public void displayName() {
System.out.println(name);
}
private void displayAge() {
System.out.println(age);
}
}
In this example, name and displayName() are public, so they can be accessed from other packages when the class itself is accessible. The age field and displayAge() method are private and can be accessed directly only within the declaring class.
14. Static Imports in Java
A static import allows accessible static members of a class or interface to be used without qualifying them with the declaring type's name. Static imports can make some code more concise, but should be used carefully to maintain readability.
Example
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) {
double radius = 5;
double area = PI * radius * radius;
System.out.println("Area: " + area);
System.out.println("Square root: " + sqrt(25));
}
}
Output
Area: 78.53981633974483
Square root: 5.0
Because PI and sqrt() are statically imported, the program can use them without writing Math.PI or Math.sqrt().
15. Compiling and Running Java Programs With Packages
When using packages from the command line, the compiler and Java launcher need to locate the source files and compiled classes through the appropriate directory structure and classpath.
Example Directory Structure
Project/
src/
mypackage/
Calculator.java
Main.java
out/
Step 1: Compile the Source Files
Run the following commands from the Project directory in a terminal where the JDK is installed:
javac -d out src/mypackage/Calculator.java src/Main.java
The -d out option tells the compiler to place the generated class files in the out directory while preserving the package structure.
Step 2: Run the Main Class
java -cp out Main
The -cp out option specifies the directory containing the compiled classes. If the main class itself belongs to a named package, use its fully qualified name when launching it.
Example With a Packaged Main Class
java -cp out com.example.Main
The fully qualified name is required because Java locates the main class by its package and class name.
16. Common Mistakes When Working With Packages
- Incorrect package declaration: Check spelling and ensure the package declaration matches the intended package name.
- Wrong directory structure: In conventional source layouts, place files in directories that match their package names.
- Missing imports: Import the required type or use its fully qualified name.
- Incorrect classpath: Ensure the compiler and Java launcher can locate the compiled classes.
- Trying to import a subpackage automatically: Remember that wildcard imports do not include subpackages.
- Accessing package-private members from another package: Use a suitable public API or revise the design when cross-package access is required.
- Using duplicate simple names without qualification: Use fully qualified names when class names conflict.
- Importing from the default package: Move the class into a named package if it needs to be used by classes in named packages.
17. Best Practices for Java Packages
- Use named packages for application code.
- Organize classes according to clear responsibilities.
- Follow consistent lowercase package naming conventions.
- Use meaningful names instead of vague package names.
- Keep package dependencies simple and avoid unnecessary circular dependencies.
- Use public access only where external access is needed.
- Prefer explicit imports when they make dependencies easier to understand.
- Use fully qualified names when different packages contain types with the same name.
- Maintain a consistent project structure in your IDE and build configuration.
- Separate application models, services, repositories, and utilities when the project benefits from that structure.
18. Practical Project: Student Management Package
Create a small Student Management program that demonstrates how to create a user-defined package and use its public class from another package.
File 1: Student.java
Place this file in the student directory.
package student;
public class Student {
private String name;
private int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
public void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}
}
File 2: Main.java
Place this file in the source root, outside the student package directory.
import student.Student;
public class Main {
public static void main(String[] args) {
Student student = new Student("Neha", 101);
student.displayDetails();
}
}
Output
Student Name: Neha
Roll Number: 101
Project Explanation
- The
Student class belongs to the student package.
- The class uses private fields to protect its internal data.
- The public constructor initializes the student's information.
- The public
displayDetails() method provides access to the required output.
- The
Main class imports and uses the Student class from another package.
19. Practice Exercises
Exercise 1: Create a Calculator Package
Create a package named calculator with a class containing addition, subtraction, multiplication, and division methods. Import and use the class in a separate main program.
Exercise 2: Create an Employee Package
Create a package named employee with an Employee class containing a name, employee ID, and a method to display employee information.
Exercise 3: Explore Built-in Packages
Write a program that uses ArrayList from java.util and LocalDate from java.time.
Exercise 4: Compare Fully Qualified Names
Use java.util.Date and java.sql.Date in the same program. Explain why their fully qualified names are different.
Exercise 5: Practice Access Control
Create two classes in the same package and another class in a different package. Test access to public, protected, package-private, and private members, and record the results.
20. Interview Questions and Answers
Q1. What is a package in Java?
Answer: A package is a namespace used to group related classes, interfaces, and other types. It improves code organization, helps prevent naming conflicts, and works with access-control rules.
Q2. What are the main types of packages in Java?
Answer: Packages are commonly categorized as built-in packages supplied by the Java platform and user-defined packages created by developers.
Q3. Which keyword is used to declare a package?
Answer: The package keyword declares the package to which a source file's top-level types belong.
Q4. Which keyword is used to import a class?
Answer: The import keyword makes accessible types available by their simple names.
Q5. What is the difference between package and import?
Answer: The package declaration identifies the package to which a type belongs. The import declaration allows types from other packages to be referenced more conveniently.
Q6. What is a fully qualified class name?
Answer: It is the complete name of a class, including its package name. For example, java.util.ArrayList.
Q7. What is the default package?
Answer: It is the unnamed package used by source files that do not declare a package.
Q8. Does importing a package import its subpackages?
Answer: No. A wildcard import such as import java.util.*; applies to accessible types directly in java.util, not to its subpackages.
Q9. What is the purpose of the java.lang package?
Answer: It contains fundamental Java language classes, including String, Object, System, and Math. Types from java.lang are automatically available by their simple names.
Q10. Can two packages contain classes with the same name?
Answer: Yes. For example, java.util.Date and java.sql.Date have the same simple class name but belong to different packages.
Q11. What is a static import?
Answer: A static import allows accessible static fields and methods to be used without qualifying them with their declaring type's name.
Q12. Why are package naming conventions important?
Answer: Consistent naming conventions improve readability, organization, and the likelihood of avoiding package-name conflicts across projects.
21. Quick Revision Checklist
- Understand what a Java package is.
- Know the difference between built-in and user-defined packages.
- Use the
package keyword correctly.
- Import individual classes with the
import keyword.
- Understand wildcard imports and their limitations.
- Recognize fully qualified class names.
- Follow package naming conventions.
- Understand the relationship between package boundaries and access modifiers.
- Compile and run packaged classes using the appropriate classpath.
- Practice creating a package and using its public classes from another package.
22. Conclusion
Java packages are essential for organizing code into logical and maintainable units. They help avoid naming conflicts, provide a foundation for package-level access control, and make it easier to reuse classes across an application.
By learning the package and import keywords, understanding built-in packages, creating user-defined packages, and practicing compilation, you can build a strong foundation for developing structured Java applications.
Continue Learning Core Java
Explore the Core Java Training Course to continue learning Java fundamentals, object-oriented programming, and other essential programming concepts.
Register for a Course Demo to learn more about the available training options.
Visit the JustAcademy official website for additional information and learning resources.