Lesson 43 of 50 – Java Packages
86%

Java Packages

A package in Java is used to organize related classes, interfaces, and other types. Packages help organize large programs, avoid naming conflicts, and control access.

1. What Is a Package in Java?

A package groups related Java classes and interfaces under a common name.

For example, a school management application might contain:

  • student package for student-related classes.
  • teacher package for teacher-related classes.
  • fees package for fee management.
package student;

public class Student {
    public void display() {
        System.out.println("Student details");
    }
}

The package declaration identifies the package to which the class belongs.

2. Types of Packages
Type Description Examples
Built-in packages Provided by the Java platform. java.util, java.io
User-defined packages Created by developers to organize application code. student, school
Packages provide a namespace, so classes with the same simple name can exist in different packages.
3. Creating a User-Defined Package

Create a Java file named Student.java inside a folder named student.

File: student/Student.java

package student;

public class Student {
    public void show() {
        System.out.println("Welcome to Java Packages");
    }
}

The package declaration must appear before the class declaration, except for comments and annotations allowed before it.

Example folder structure:

MyProject/
└── student/
    └── Student.java
4. Using a Class from Another Package

You can import a public class from another package and create its object.

File: student/Student.java

package student;

public class Student {
    public void show() {
        System.out.println("Student class called");
    }
}

File: Main.java

import student.Student;

class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.show();
    }
}
Output:
Student class called

The Main class imports Student using its package name and then creates an object.

5. The import Keyword

The import keyword allows you to refer to accessible types by their simple names rather than writing their fully qualified names each time.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.println("Hello " + name);

        sc.close();
    }
}
Example Output:
Enter your name: Rahul
Hello Rahul

Here, Scanner belongs to the java.util package.

6. Importing Multiple Classes

You can import multiple classes from the same package using separate import statements.

import java.util.Scanner;
import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        ArrayList names = new ArrayList<>();

        names.add("Rahul");
        names.add("Priya");

        System.out.println(names);

        sc.close();
    }
}
Output:
[Rahul, Priya]

Both Scanner and ArrayList are in the java.util package.

7. Importing an Entire Package

You can use a wildcard import to make accessible types in a package available by their simple names.

import java.util.*;

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

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");

        System.out.println(fruits);
    }
}
Output:
[Apple, Mango, Banana]

The * wildcard imports accessible types declared in that package. It does not automatically import classes from its subpackages.

8. Common Built-in Java Packages
Package Purpose Common Types
java.lang Core language classes. String, Math, System
java.util Collections and utilities. Scanner, ArrayList, HashMap
java.io Traditional input/output. File, FileReader, BufferedReader
java.nio.file Modern file and path operations. Path, Files
java.time Date and time operations. LocalDate, LocalTime
java.net Networking. URL, Socket
Classes in java.lang are automatically available by simple name in ordinary Java source files. Other packages generally need imports or fully qualified names.
9. Using a Fully Qualified Class Name

A fully qualified class name includes the package name followed by the class name. You can use it without an import statement.

class Main {
    public static void main(String[] args) {
        java.util.ArrayList names =
            new java.util.ArrayList<>();

        names.add("Rahul");
        names.add("Amit");

        System.out.println(names);
    }
}
Output:
[Rahul, Amit]

The fully qualified name is java.util.ArrayList.

10. Package Structure in a Java Project

A project can contain multiple packages to organize its classes by responsibility.

SchoolProject/
├── Main.java
├── student/
│   └── Student.java
├── teacher/
│   └── Teacher.java
└── fees/
    └── FeeManager.java

Each class can declare its corresponding package. For example, Student.java begins with package student;.

A typical source file places its package declaration first, followed by imports and then its type declarations.

11. Compiling and Running Packaged Java Classes

Suppose your project contains these files:

MyProject/
├── Main.java
└── student/
    └── Student.java

The Student.java file contains package student;, and Main.java imports student.Student.

Step 1: Open a terminal in MyProject.

Step 2: Compile both source files.

javac -d . Main.java student/Student.java

The -d . option tells the compiler to place generated class files in the current directory structure according to their packages.

Step 3: Run the Main class.

java Main
Output:
Student class called
Important: Run the java command from the project root so Java can find the packaged class.
12. Advantages of Packages
  • Organize related classes and interfaces.
  • Reduce naming conflicts between types.
  • Support package-level access control.
  • Make large projects easier to maintain.
  • Improve code reuse and project structure.
Important Note

Importing a class does not grant additional access to private or package-private members. Access still depends on Java's access rules.

13. Practice Assignments
  1. Create a package named student and add a Student class with a display() method.
  2. Create Main.java outside the student package and import the Student class.
  3. Write a program using Scanner from java.util to accept a student's name.
  4. Use ArrayList from java.util to store five student names.
  5. Print the current date using java.time.LocalDate.
  6. Create separate student and teacher packages in one project.
  7. Compile and run a packaged Java project using the terminal.
Practice Tip: Keep the folder structure consistent with each package declaration and practise compiling the project from its root directory.

🧠 Quick Quiz

1. Which keyword declares a package in Java?




2. Which package contains the Scanner class?




3. What does the import keyword help you do?