Course Content
Core Java
About Lesson

To create a package, you simply declare it at the top of your Java source file using the package keyword, followed by the package name.

Steps to create and use a package

  1. Define the package
  2. Organize the directory structure
  3. Compile the package
  4. Run the Program

Define the package

Package is defined using keyword package followed by the package name at the first line of your source file.

package com.example.utils;

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

    public static int subtract(int a, int b) {
        return a - b;
    }
}

Organize the Directory Structure

The directory structure should match the package name. Each level of the package name corresponds to a directory.

src/
└── com/
    └── example/
        └── utils/
            └── MathUtils.java

Compile the Package

javac is used to compile the source file created. We use -d <director_name> option with javac. Using this if  a class is part of a package, then javac puts the class file in a subdirectory that reflects the module name (if appropriate) and package name. The directory, and any necessary subdirectories, will be created if they do not already exist.

javac -d out src/com/example/utils/MathUtils.java

This command compiles the MathUtils.java file and places the resulting .class file in the out directory, maintaining the package structure.

Run the Program

java -cp out com.example.utils.MathUtils

-cp <path> specifies where to find the user class files.

Use the Package

To use a class from a package, you need to import it using the import statement in your Java file. This statement should be placed after the package declaration (if any) and before the class declaration.

package com.example.app;

import com.example.utils.MathUtils;  // Importing the MathUtils class

public class Main {
    public static void main(String[] args) {
        int sum = MathUtils.add(5, 3);
        int difference = MathUtils.subtract(5, 3);

        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
    }
}

Compile the program

javac -d out src/com/example/utils/MathUtils.java src/com/example/app/App.java

Run the Program

java -cp out com.example.app.App

Scroll to Top