C

Core Java tutorial for beginners

Clean • Professional

Java – Creating and Importing Packages (Step-by-Step Guide)

3 minute

Creating & Importing Packages in Java

In Java, packages are used to organize classes and interfaces into separate namespaces.

They help make large projects more manageable, reusable, and prevent class name conflicts.


Creating a User-Defined Package

learn code with durgesh images

Step 1: Declare the Package

You must declare the package at the top of your Java file (before imports or class definitions).

// File: mypack/Message.java
package mypack;

public class Message {
    public void show() {
        System.out.println("Hello from mypack!");
    }
}

Note: The folder name must match the package name (mypack).


Step 2: Compile the Program

Use the -d option with the compiler to generate the correct folder structure:

javac -d . Message.java

Explanation:

  • d . → tells the compiler to place compiled files in a directory structure based on the package.
  • . → current working directory.

After compiling, you’ll get this structure:

|-- mypack
    |-- Message.class

Step 3: Import and Use the Package

Now, create another file to use the class from the package.

// File: TestPackage.java
import mypack.Message; // importing class

public class TestPackage {
    public static void main(String[] args) {
        Message msg = new Message();
        msg.show();
    }
}

Run it:

java TestPackage

Output:

Hello from mypack!

Importing Packages

There are three ways to import classes from a package:

learn code with durgesh images

1. Import a Single Class

import mypack.Message;

2. Import All Classes in a Package

import mypack.*;

3. Use Fully Qualified Class Name

public class Main {
    public static void main(String[] args) {
        mypack.Message msg = new mypack.Message();
        msg.show();
    }
}

Works without import, but not recommended for large codebases.


Points to Remember

  • Always use package keyword at the top of the file.
  • Folder name must match the package name.
  • Use import to access classes from other packages.
  • Compile using javac -d . to maintain proper directory structure.
  • Classes you want to use outside the package must be public.

Article 0 of 0