Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java package Keyword
Usage and Examples



package Keyword in Java

In Java, the package keyword is used to define a namespace for classes and interfaces. It plays a fundamental role in organizing your code into modular units, allowing better maintainability, avoiding name conflicts, and making your application structure cleaner.

Why Use Packages?

Imagine working on a large application with hundreds of classes. If all of them were dumped into one folder, it would quickly become overwhelming. Packages help by:

Syntax of the package Keyword

The package declaration must be the first line of your Java source file, before any import statements or class definitions.

package com.example.myapp;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello from my package!");
    }
}

Creating and Using Packages – Step by Step

Step 1: Declare the Package

At the very top of your Java file, write:

package mypackage;

This tells the compiler that this class belongs to the mypackage namespace.

Step 2: Save the File in a Directory Matching the Package Name

Save the file in a directory named mypackage.

For example:


/project-root/
  └── mypackage/
      └── HelloWorld.java

Step 3: Compile the Java File

Navigate to the root directory and compile using:


javac mypackage/HelloWorld.java

Step 4: Run the Class

To run a class in a package, use the fully qualified name:


java mypackage.HelloWorld
Hello from my package!

Accessing a Class from Another Package

You can access a class from another package by importing it using the import keyword.

Example

Step 1: A class in utilities package:

// File: utilities/MessagePrinter.java
package utilities;

public class MessagePrinter {
    public void printMessage() {
        System.out.println("Message from utilities package.");
    }
}

Step 2: Accessing this class from another package:

// File: app/Main.java
package app;

import utilities.MessagePrinter;

public class Main {
    public static void main(String[] args) {
        MessagePrinter printer = new MessagePrinter();
        printer.printMessage();
    }
}
Message from utilities package.

Types of Packages in Java

Package Naming Conventions

It’s standard to use your organization’s internet domain name in reverse as the prefix, followed by the project/module name. For example:

package com.tutorialkart.datastructures;

Best Practices

Common Mistakes



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M