Popular Searches
Popular Course Categories
Popular Courses

Using the package Declaration

Using the package Declaration

Packages, Imports, and Java API Fundamentals

Using the Package Declaration in Java

Course: Core Java Training

Topic: Using the Package Declaration in Java

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Package Declaration

In Java, a package declaration specifies the package to which a class or other top-level type belongs. It helps organize related classes and interfaces into logical groups, making Java applications easier to maintain, understand, and reuse.

The package keyword is used to declare a package. When a Java source file contains a package declaration, its top-level types belong to that named package. The package name also forms part of the fully qualified name of each type declared within it.

For example, if a class named Student belongs to the package com.example.school, its fully qualified name is com.example.school.Student.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the purpose of package declarations in Java.
  • Use the package keyword correctly.
  • Write package declarations in Java source files.
  • Understand the relationship between package names and directory structures.
  • Create and use classes inside user-defined packages.
  • Access packaged classes using imports and fully qualified names.
  • Compile and run Java programs that use package declarations.
  • Understand package naming conventions and access control.
  • Identify and resolve common package declaration errors.

3. What Is a Package Declaration?

A package declaration is a statement at the beginning of a Java source file that identifies the package associated with its top-level types.

Syntax

package packageName;

Here, package is the Java keyword, packageName is the name of the package, and the semicolon terminates the declaration.

Example

package com.example.student;

public class Student {
    public void display() {
        System.out.println("Welcome to the Student Package");
    }
}

Explanation: The declaration package com.example.student; places the Student class in the com.example.student package.

4. Why Is a Package Declaration Important?

Package declarations are useful for several reasons.

4.1 Organizing Classes

Package declarations help group related classes together. For example, an application may have separate packages for customers, products, payments, and reports.

4.2 Preventing Naming Conflicts

Two packages can contain classes with the same simple name. Their fully qualified names distinguish them.

com.company.sales.Employee
com.company.hr.Employee

Both classes are named Employee, but each belongs to a different package.

4.3 Supporting Access Control

Package membership affects access to package-private classes and members. It also determines whether classes can access protected members under Java's access-control rules.

4.4 Improving Maintainability

Package declarations help developers locate related functionality and understand the structure of large projects.

4.5 Supporting Reusability

Public classes and interfaces in named packages can be reused by other classes when they are available through the appropriate classpath or module configuration.

5. Rules for Writing Package Declarations

Java package declarations follow several important rules.

  • A package declaration is optional. If omitted, the source file's types belong to an unnamed package.
  • When present, the package declaration must appear before import declarations and type declarations, apart from permitted annotations and comments.
  • The declaration must use the package keyword.
  • The package name must be a valid sequence of identifiers separated by periods.
  • The statement must end with a semicolon.
  • Use lowercase letters in package names as a common naming convention.
  • In conventional filesystem-based projects, the directory structure should correspond to the package name.
  • A source file can declare only one package for its top-level types.

Correct Example

package com.example.library;

import java.util.ArrayList;

public class Book {
    public void display() {
        System.out.println("Java Package Declaration");
    }
}

Incorrect Example

import java.util.ArrayList;

package com.example.library;

public class Book {
}

Why is it incorrect? The package declaration appears after an import statement. In an ordinary Java compilation unit, the package declaration must precede import declarations.

6. Understanding Package Names

A package name can contain multiple components separated by periods. Each component identifies a level in the package's naming hierarchy.

Example

package com.justacademy.java.basics;

This package name contains the following components:

Component Meaning
com A commonly used top-level naming component.
justacademy An organization or project identifier.
java A category for Java-related code.
basics A more specific group of classes.

These components help organize types into a consistent namespace. Package names are case-sensitive, so com.example and com.Example are different package names.

7. Package Declaration and Directory Structure

In a conventional Java project, package names correspond to directory paths under the source root. Each period in the package name generally corresponds to a directory separator.

Example Package Declaration

package com.example.student;

Corresponding Directory Structure

JavaProject/
    src/
        com/
            example/
                student/
                    Student.java

Here, Student.java is stored inside the student directory. The directories com and example represent the preceding package components.

Important: The Java compiler can sometimes compile source files whose physical locations do not match their package declarations when files are supplied explicitly. However, following the conventional directory structure is strongly recommended for predictable builds and easier project maintenance.

8. Creating a User-Defined Package

A user-defined package is a package created by a developer to organize application-specific classes.

Step 1: Create the Package Directory

Create the following directory structure:

JavaProject/
    src/
        calculator/

Step 2: Create Calculator.java

Inside the calculator directory, create a file named Calculator.java.

package calculator;

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }
}

The first statement declares that the Calculator class belongs to the calculator package.

Step 3: Create Main.java

Create a Main.java file in the src directory.

import calculator.Calculator;

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println("Addition: " + calc.add(10, 5));
        System.out.println("Multiplication: " + calc.multiply(10, 5));
    }
}

Output

Addition: 15
Multiplication: 50

Explanation: The Calculator class belongs to a named package. The Main class imports it and uses its public methods.

9. Using a Package Without an Import Statement

A class from another package can be referenced by its fully qualified name instead of importing it. This is useful when only one reference is needed or when different packages contain classes with the same simple name.

Example

public class Main {
    public static void main(String[] args) {
        calculator.Calculator calc =
            new calculator.Calculator();

        System.out.println(calc.add(20, 10));
    }
}

Output

30

The fully qualified name calculator.Calculator identifies the class without an import statement.

10. Difference Between package and import

Feature package import
Purpose Declares the package associated with top-level types. Allows types from other packages to be referenced by simple names.
Keyword package import
Location Before import declarations in a standard source file. After the package declaration and before type declarations.
Requirement Optional in Java source files. Optional; types may also be referenced by fully qualified names.
Example package com.example; import java.util.Scanner;

11. Built-in Packages and Package Declarations

Java provides many built-in packages. When using a class from a built-in package, you generally do not declare that package in your own source file. Instead, you import the class or refer to it by its fully qualified name.

Package Purpose Example
java.lang Fundamental language classes. String, System, Math
java.util Collections and utility classes. ArrayList, Scanner
java.io Input and output functionality. File, BufferedReader
java.time Date and time functionality. LocalDate, LocalDateTime
java.sql JDBC database access. Connection, ResultSet

Example

package com.example.demo;

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> subjects = new ArrayList<>();

        subjects.add("Java");
        subjects.add("SQL");
        subjects.add("OOP");

        System.out.println(subjects);
    }
}

Output

[Java, SQL, OOP]

The class belongs to the user-defined package com.example.demo and imports the built-in ArrayList type from java.util.

12. Package Declaration and Access Modifiers

Package declarations affect access control because Java uses package membership to determine whether certain classes and members can be accessed.

Access Modifier Access Within Same Package Access From Another Package
public Yes Yes, when the declaring type and other access requirements permit it.
protected Yes Available to subclasses under Java's protected-access rules.
No modifier (package-private) Yes No direct access.
private No direct access from other top-level classes No direct access from other classes.

Example

package com.example;

public class Employee {
    public String name = "Amit";
    int employeeId = 101;
    private double salary = 30000;

    public void displayName() {
        System.out.println(name);
    }
}

The field name is public and can be accessed from another package if the class is accessible. The field employeeId is package-private and can be accessed directly by classes in the same package. The field salary is private and can be accessed directly only within the declaring class.

13. Naming Conventions for Package Declarations

Consistent package naming improves readability and reduces the risk of naming conflicts.

  • Use lowercase letters for package names.
  • Separate package components with periods.
  • Use meaningful names that describe the purpose of the code.
  • Use a reversed domain name as a prefix when appropriate.
  • Avoid Java reserved keywords as package-name components.
  • Keep package names consistent throughout the project.

Examples

com.company.employee
com.company.billing
org.example.inventory
in.justacademy.corejava

Avoid unclear names such as package1, abc, or xyz in production projects.

14. Compiling and Running a Program With a Package Declaration

Java programs that use named packages must be compiled and executed with the correct source structure and classpath.

Project Structure

JavaProject/
    src/
        calculator/
            Calculator.java
        Main.java
    out/

Step 1: Open a Terminal

Open a terminal in the JavaProject directory and make sure a JDK is installed and available on your system path.

Step 2: Compile the Java Files

javac -d out src/calculator/Calculator.java src/Main.java

The -d out option directs the compiler to place generated class files in the out directory, preserving the package structure.

Step 3: Run the Program

java -cp out Main

The -cp out option tells Java where to find the compiled classes.

If the main class also belongs to a named package, run it using its fully qualified name. For example:

java -cp out com.example.Main

15. Common Errors in Package Declarations

15.1 Package Declaration in the Wrong Position

Problem: An import statement or class declaration appears before the package declaration.

Solution: Move the package declaration to the beginning of the source file, before imports and type declarations.

15.2 Package Name Does Not Match the Intended Structure

Problem: The source file declares package com.example.student; but is placed in an unrelated directory in a conventional project.

Solution: Organize the source directory to match the package name and confirm the compiler's source root.

15.3 Class Not Found

Problem: Java cannot locate the compiled class at runtime.

Solution: Check the output directory, classpath, and fully qualified main-class name.

15.4 Cannot Access a Class

Problem: A class from another package is inaccessible.

Solution: Check that the class is declared public if cross-package access is required and verify the access level of its constructor and methods.

15.5 Importing a Class From the Default Package

Problem: A class in a named package tries to import a class from the unnamed package.

Solution: Move the class into a named package and update the imports and directory structure.

16. Best Practices for Package Declarations

  • Declare a meaningful named package for application classes.
  • Use lowercase, descriptive package names.
  • Keep related classes together.
  • Maintain a consistent directory structure in conventional Java projects.
  • Place package declarations before imports and type declarations.
  • Use public classes only when they need to be accessed outside their package.
  • Keep internal implementation details package-private or private when appropriate.
  • Avoid placing production application code in the unnamed package.
  • Use fully qualified class names when different packages contain types with the same name.
  • Verify compilation and runtime classpath settings when working with packaged classes.

17. Practical Project: Employee Management Package

In this project, you will create an Employee class inside a user-defined package and access it from another class.

File 1: Employee.java

Create the file inside the employee directory.

package employee;

public class Employee {
    private String name;
    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public void displayDetails() {
        System.out.println("Employee Name: " + name);
        System.out.println("Employee ID: " + id);
    }
}

File 2: Main.java

Create this file in the source root, outside the employee directory.

import employee.Employee;

public class Main {
    public static void main(String[] args) {
        Employee employee = new Employee("Priya", 102);
        employee.displayDetails();
    }
}

Output

Employee Name: Priya
Employee ID: 102

What You Learned

  • The Employee class belongs to the employee package.
  • The package declaration identifies the class's namespace.
  • The import statement allows the main program to refer to the class by its simple name.
  • Private fields protect the employee's internal data.
  • Public constructors and methods allow controlled access from other packages.

18. Practice Exercises

Exercise 1: Create a Student Package

Create a package named student containing a Student class with a name, roll number, and a method to display details. Use this class from a separate Main class.

Exercise 2: Create a Calculator Package

Create a package named calculator with methods for addition, subtraction, multiplication, and division. Import the Calculator class into another source file.

Exercise 3: Use Fully Qualified Names

Create a program that uses a class from a user-defined package without an import statement. Use its fully qualified name to create an object.

Exercise 4: Explore Access Modifiers

Create two classes in the same package and one class in a different package. Test access to public, protected, package-private, and private members.

Exercise 5: Compile a Packaged Program

Create a project with a package declaration, compile it using the -d option, and run the main class using the correct classpath.

19. Interview Questions and Answers

Q1. What is a package declaration in Java?

Answer: A package declaration specifies the package associated with the top-level types in a Java source file. It uses the package keyword.

Q2. Is a package declaration mandatory?

Answer: No. If it is omitted, the source file's types belong to an unnamed package.

Q3. Where should a package declaration appear?

Answer: It must appear before import declarations and type declarations, apart from permitted annotations and comments.

Q4. Can one Java source file declare multiple packages?

Answer: No. A Java source file can have only one package declaration for its top-level types.

Q5. What is a fully qualified class name?

Answer: It is the complete name of a class, including its package name, such as java.util.ArrayList.

Q6. What is the relationship between package names and directories?

Answer: In a conventional filesystem-based Java project, each package component corresponds to a directory beneath the source root.

Q7. What happens if the package declaration is omitted?

Answer: The top-level types belong to the unnamed package. Classes in named packages cannot import types from the unnamed package.

Q8. Can two packages have classes with the same name?

Answer: Yes. Their fully qualified names distinguish them.

Q9. What is the difference between a package declaration and an import statement?

Answer: A package declaration identifies the package of the source file's types, while an import statement allows types from other packages to be referenced by simple names.

Q10. Why should package names generally use lowercase letters?

Answer: Lowercase package names follow standard Java naming conventions and help maintain consistency and readability.

20. Quick Revision Checklist

  • Understand the purpose of the package keyword.
  • Know the syntax of a package declaration.
  • Place the package declaration in the correct position.
  • Understand package names and fully qualified class names.
  • Follow conventional package-to-directory mapping.
  • Know how to import and use packaged classes.
  • Understand the relationship between package boundaries and access modifiers.
  • Compile packaged classes with the correct output directory.
  • Run programs with the appropriate classpath.
  • Practice creating and using your own packages.

21. Conclusion

Package declarations are an important part of Java programming because they identify the namespace of classes and help organize source code into logical groups. By using the package keyword correctly, developers can build structured applications, reduce naming conflicts, and work more effectively with access control.

Understanding package declarations, directory structures, imports, fully qualified class names, and compilation commands provides a strong foundation for developing maintainable Java applications.


Continue Learning Core Java with JustAcademy

Explore the Core Java Training Course to strengthen your understanding of Java fundamentals, object-oriented programming, packages, classes, and other essential concepts.

Register for a Course Demo to learn more about the available training options.

Visit the JustAcademy Official Website for additional course information and learning resources.

Previous Next
whatsapp