Topic 72 of 119 6. Object-Oriented Programming in Java Interactive Tutorial

Package Management in Java: Organization, Namespaces, and Imports

9 mins read Last updated: 22 Aug 2026 27,456 views

Direct Answer & Core Concept

A Java package is a namespace that groups related classes, interfaces, and subpackages. Packages correspond to directory structures on the filesystem, prevent class naming collisions, provide package-private access encapsulation, and ease class discovery through import statements.

Detailed Explanation & Mechanics

Package Management in Java: Organization, Namespaces, and Imports

Introduction

As a Java project becomes larger, keeping every class in one place can make the code difficult to understand. Java packages provide a simple way to group related classes, interfaces, and other types together.

Packages also help avoid naming conflicts and make it easier to control access between different parts of an application. In this tutorial, you will learn how Java packages work, how to create them, and how to use imports.


What Is a Package in Java?

A package in Java is a way of grouping related classes and interfaces under a common name. You can think of it as a folder that keeps similar Java files organized.

For example, an application might have separate packages for users, payments, products, and orders. This makes a large Java project easier to navigate and maintain.

Main.java
Run Online
package com.example.users;
public class User {
    String name;
}

Here, com.example.users is the package name and User belongs to that package.


Why Are Packages Used in Java?

Packages are useful when a project contains many classes and files. They give the application a clear structure instead of putting everything into one large collection.

They also help prevent class-name conflicts. For example, two different packages can contain a class named User without causing a problem.

Main benefits of packages

  • Organize related classes

  • Avoid naming conflicts

  • Control access to classes and members

  • Make large applications easier to maintain

  • Reuse code between different parts of a project


Java Package Syntax

A package is declared using the package keyword. The package declaration normally appears at the beginning of the Java source file.

Main.java
Run Online
package com.example.school;
public class Student {
}

The package declaration tells Java that the Student class belongs to com.example.school.


Package Declaration in Java

The package declaration should appear before the class definition and after any comments or documentation at the top of the file.

Main.java
Run Online
package com.example;
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello Java");
    }
}

A Java source file can have only one package declaration. The declaration applies to the types defined in that source file.


Java Package Naming Convention

Java package names are normally written using lowercase letters. A common naming style starts with a reversed domain name, followed by the project or feature name.

For example:

Main.java
Run Online
com.company.applicationcom.company.application.usercom.company.application.payment

Using a consistent naming convention makes packages easier to understand, especially in large applications.


Package Names and Folder Structure

Java packages are normally represented by matching directory structures. Each part of the package name corresponds to a directory.

For example:

can have a directory structure like:

Architecture Diagram
com/
└── example/
    └── shop/
        ├── Product.java
        └── Order.java

This structure helps Java tools locate compiled classes and source files correctly.


What Is a Namespace in Java?

A namespace is a naming space that helps distinguish one name from another. Java packages provide namespace-like organization for classes and other types.

For example, both of these packages could contain a class named User:

Main.java
Run Online
com.company.admin.Usercom.company.customer.User

The complete names are different, so Java can distinguish between the two classes.


Fully Qualified Class Name

A fully qualified class name contains the complete package name followed by the class name.

For example:

Here:

is the package name, while:

is the class name.

You can use the complete name directly in Java code when necessary.


Example of a Fully Qualified Class Name

Suppose you have a class named DateFormatter inside the package com.example.utils.

You can create its object like this:

Main.java
Run Online
com.example.utils.DateFormatter formatter = new com.example.utils.DateFormatter();

This approach avoids an import statement, but it can make the code harder to read when the class is used many times.


What Is an Import in Java?

The import keyword allows you to use a class from another package without writing its complete package name every time.

For example:

Main.java
Run Online
import java.util.Scanner;

After importing Scanner, you can simply write:

Main.java
Run Online
Scanner input = new Scanner(System.in);

Imports make Java code shorter and easier to read.


How to Import a Java Class

The basic syntax for importing a class is:

Main.java
Run Online
import packageName.ClassName;

For example:

Main.java
Run Online
import java.util.ArrayList;

Now the ArrayList class can be used directly in the source file.

Main.java
Run Online
ArrayList<String> names = new ArrayList<>();

Import Multiple Classes

A Java file can import several classes from different packages. Each import statement is written separately.

Main.java
Run Online
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

This is useful when a program needs several classes from the Java standard library or from external libraries.


Import All Classes from a Package

Java also supports the wildcard * for importing accessible types from a package.

Now classes such as ArrayList, HashMap, and Scanner can be referenced without their full package names.

However, using specific imports can make it clearer which classes the program actually uses.


Importing a Static Member

Java also allows static fields and methods to be imported.

For example:

Main.java
Run Online
import static java.lang.Math.PI;

You can then use:

Without static import, you would normally write:

Main.java
Run Online
System.out.println(Math.PI);

Static imports can be convenient, but they should be used carefully to keep code understandable.


Importing Static Methods

You can also import a static method.

Main.java
Run Online
import static java.lang.Math.sqrt;

Then you can write:

Main.java
Run Online
double result = sqrt(25);
System.out.println(result);

Without the static import, the code would be:

Main.java
Run Online
double result = Math.sqrt(25);

The second style can sometimes be easier for beginners to recognize.


Do We Need to Import Classes from the Same Package?

No. A class does not need to import another class when both classes belong to the same package.

For example:

Main.java
Run Online
package com.example.shop;
public class Product {
}

Another class in the same package can directly use Product.

Main.java
Run Online
package com.example.shop;
public class Store {
    Product product = new Product();
}

No import statement is required here.


Do We Need to Import java.lang Classes?

Java automatically makes the classes in the java.lang package available to every Java source file.

For example, you can use:

Main.java
Run Online
String name = "Tanmoy";
System.out.println(name);

You do not normally need to write:

Classes such as String, System, and Math are commonly available without explicit imports.


Package and Import Difference

The package statement tells Java where a class belongs. The import statement tells Java which classes from other packages you want to use by their simple names.

Main.java
Run Online
package com.example.app;
import java.util.Scanner;

Here, package defines the current class's package, while import brings another type into convenient use.


Package vs Import

FeaturePackageImport
Keywordpackageimport
PurposeOrganizes a classUses a type from another package
LocationUsually first statementAfter package declaration
Examplepackage com.example;import java.util.Scanner;
Main benefitOrganizationEasier class references

Creating a Simple Custom Package

Let's create a small package containing a Student class.

Main.java
Run Online
package school;
public class Student {
    public void showName() {
        System.out.println("Student class");
    }
}

Another class can import it:

Main.java
Run Online
import school.Student;
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.showName();
    }
}

This is one of the most common ways packages are used in Java applications.


Package Access and Default Members

Packages are also connected to Java access control. A class member without an access modifier has package-level access.

For example:

Main.java
Run Online
package school;
class Student {
    int age = 20;
}

The age field can be accessed by compatible code in the same package, but it is not generally accessible from another package.

This is called default or package-private access.


Public Classes Across Packages

A public class can be accessed from another package when it is available to that code.

For example:

Main.java
Run Online
package school;
public class Student {
    public void display() {
        System.out.println("Hello");
    }
}

Another package can import and use the class:

Main.java
Run Online
import school.Student;
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.display();
    }
}

Package Management with Java Collections

Java's standard library contains many packages. The java.util package, for example, contains commonly used collection classes.

Main.java
Run Online
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

You can then use these classes directly in your application without writing their complete package names.


Common Java Packages

Java provides many useful standard packages.

PackageCommon Purpose
java.langCore Java classes
java.utilCollections and utility classes
java.ioInput and output
java.nioModern file and data operations
java.netNetworking
java.timeDate and time API
java.sqlDatabase-related APIs

Learning commonly used packages makes Java programming much easier.


Wildcard Import Example

A wildcard import can be used when several classes from the same package are required.

Now the program can use classes such as:

Main.java
Run Online
ArrayList<String> list = new ArrayList<>();
HashMap<Integer, String> users = new HashMap<>();

The wildcard does not mean that classes from subpackages are automatically imported.


Packages and Subpackages

A package can be organized into smaller package names.

For example:

Main.java
Run Online
com.companycom.company.usercom.company.paymentcom.company.order

These names create a logical hierarchy, but each package is treated as a separate package by Java.

A subpackage is not automatically considered part of the access scope of its parent package.


Package Import Does Not Import Subpackages

Consider:

This does not automatically import classes from:

Main.java
Run Online
com.company.usercom.company.payment

If you need a class from com.company.user, import that class or package explicitly.

Main.java
Run Online
import com.company.user.User;

This is an important point for beginners.


Can Two Packages Have the Same Class Name?

Yes. Two different packages can contain classes with the same simple name.

For example:

Main.java
Run Online
com.shop.Usercom.school.User

Java can distinguish them using their fully qualified names.

If both are needed in the same source file, you can use one import and refer to the other using its full package name.


Package Name Conflict Example

Suppose two packages contain a Product class:

You can use the imported class normally:

Main.java
Run Online
Product product = new Product();

For another class with the same name, use its fully qualified name:

Main.java
Run Online
com.store.Product item = new com.store.Product();

This removes ambiguity.


Package Statement vs Folder Name

In normal Java project structures, the package declaration and directory structure should match.

For example:

Main.java
Run Online
package com.example.product;

is normally stored under:

Modern Java build tools such as Maven and Gradle rely heavily on this organized project structure.


Package Management in Maven Projects

In larger Java applications, Maven is commonly used to manage project dependencies and build configuration.

A typical Java project may look like:

Architecture Diagram
src/
└── main/
    └── java/
        └── com/
            └── example/
                ├── controller/
                ├── service/
                ├── model/
                └── repository/

Packages provide the Java-level organization, while Maven manages dependencies and the project build.


Package Management in Gradle Projects

Gradle is another popular Java build tool. Java packages can be organized inside the standard source directory.

Main.java
Run Online
src/main/java/com/example/

Inside it, you might have:

Main.java
Run Online
model/service/controller/repository/

This separation makes a growing Java application easier to maintain.


Common Mistakes with Java Packages

Beginners often face package-related errors because the package name, directory structure, and import statement do not match.

Common problems include:

  • Incorrect package declaration

  • Wrong import statement

  • Class placed in the wrong directory

  • Forgetting public when cross-package access is required

  • Assuming subpackages are automatically imported

  • Using two classes with the same name without resolving the conflict


Package Declaration Must Be Correct

Consider this declaration:

Main.java
Run Online
package com.example.users;

The source file should normally be placed in a matching package directory.

If the project structure does not match the package declaration, Java tools may report compilation or class-loading problems.


Import Statement Must Use the Correct Name

Suppose the class is:

Main.java
Run Online
package com.example.users;
public class User {
}

The correct import is:

Main.java
Run Online
import com.example.users.User;

Writing an incorrect package or class name will cause a compilation error.


Package and Access Modifiers

Packages work closely with Java access modifiers. private, default, protected, and public determine how classes and members can be accessed.

In particular, default access is limited to the same package, while public members can be accessed more broadly when other requirements are satisfied.


Complete Package and Import Example

Here is a simple example using two packages.

Student.java

Main.java
Run Online
package school;
public class Student {
    public void display() {
        System.out.println("Student information");
    }
}

Main.java

Main.java
Run Online
import school.Student;
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.display();
    }
}

The Student class belongs to the school package, while Main imports and uses it.


How Java Finds an Imported Class

When Java sees:

the compiler knows that Student refers to the class located in the school package.

The import statement does not copy the class into your source file. It simply allows you to use the class name without repeatedly writing the complete package name.


Package Management in Large Java Applications

Large applications often divide code according to responsibility. For example, an online shopping application might use packages for users, products, payments, orders, and database operations.

Architecture Diagram
com.shop
├── user
├── product
├── order
├── payment
└── repository

This type of organization makes it easier for developers to locate and maintain specific parts of the application.


Best Practices for Java Packages

Use lowercase package names and keep the naming style consistent throughout the project. Group classes according to their responsibility instead of putting unrelated classes together.

Avoid unnecessarily deep package structures. A package should make the project easier to understand, not create additional complexity.


Package Management vs Class Management

A class represents a specific object, concept, or piece of functionality. A package groups related classes together.

For example:

Main.java
Run Online
Package: paymentClasses:PaymentCreditCardPaymentInvoicePaymentService

The package provides the organizational layer, while the classes provide the actual functionality.


Frequently Asked Questions

What is a package in Java?

A package is a way to group related Java classes and interfaces. It helps organize source code, reduce naming conflicts, and manage access between different parts of an application.

What is the use of the package keyword?

The package keyword declares the package to which a Java class belongs. It helps Java organize classes under a specific package name.

What is the use of import in Java?

The import keyword allows you to refer to a class or other type from another package using its simple name instead of writing the complete package name.

Can I use a class without importing it?

Yes. Classes in the same package can normally be used without an import statement. Classes from java.lang are also automatically available.

Does import java.util.* import subpackages?

No. A wildcard import applies to types directly in that package. It does not automatically import classes from subpackages.

Can two packages contain classes with the same name?

Yes. For example, com.shop.User and com.school.User can both exist. Their fully qualified names are different.

What is a fully qualified class name?

A fully qualified class name contains the package name and class name together, such as:

Is a package the same as a folder?

Not exactly. A package is a Java language concept, while folders are part of the file-system structure. In normal Java projects, the directory structure mirrors the package name.


Quick Example to Remember Packages

Think about a school building.

The building represents the Java project, each department represents a package, and the students or teachers inside each department represent classes.

Architecture Diagram
School Project
│
├── student
│   ├── Student
│   └── StudentService
│
├── teacher
│   ├── Teacher
│   └── TeacherService
│
└── library
    ├── Book
    └── LibraryService

This mental model makes Java packages easier to understand when you are starting out.


Graphic Design Idea

Create a simple educational diagram showing how Java packages organize classes:

Architecture Diagram
             JAVA PROJECT
                  │
        ┌─────────┼─────────┐
↓

↓

↓
user      payment    product
      │           │          │
   User.java   Pay.java   Product.java
      │           │          │
      └───────────┼──────────┘
↓
import statement
↓
Main.java

Use different boxes for Package, Class, and Import. Keep the design clean, with short labels so a beginner can understand the relationship within a few seconds.

Recommended Graphic Sections

Graphic 1:
“Java Package Structure” — show package → subpackage → class.

Graphic 2:
“Package vs Import” — show package defining where a class belongs and import bringing another class into use.

Graphic 3:
“Java Namespace Example” — show:

Main.java
Run Online
com.shop.Usercom.school.User

and explain that both User classes can exist because their complete names are different.

Graphic 4:
“Java Project Folder Structure” — show:

Architecture Diagram
src/
└── main/
    └── java/
        └── com/
            └── example/
                ├── user/
                ├── product/
                └── payment/

These visuals can make the page much easier for beginners to scan and understand.

Runnable Code Example: Package Management in Java

Java 17+
Main.java
Run Online
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.max;
public class PackageDemo {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>();
        items.add("Java");
        int maximum = max(10, 25);
        // static import
        System.out.println("Items: " + items + ", Max: " + maximum);
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

What package is imported automatically in all Java source files?

java.lang.* is imported implicitly by the compiler.
Q2

Does importing a package wildcard (import java.util.*) import subpackages as well?

No, wildcard imports import only classes in that immediate package, not subpackages.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Use reverse domain conventions (com.example.service) for unique root package namespaces to avoid conflicts in enterprise JAR libraries.