⬅ Previous Topic
Java null KeywordNext Topic ⮕
Java private Keywordpackage
Keyword⬅ Previous Topic
Java null KeywordNext Topic ⮕
Java private Keywordpackage
Keyword in JavaIn 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.
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:
package
KeywordThe 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!");
}
}
At the very top of your Java file, write:
package mypackage;
This tells the compiler that this class belongs to the mypackage
namespace.
Save the file in a directory named mypackage
.
For example:
/project-root/
└── mypackage/
└── HelloWorld.java
Navigate to the root directory and compile using:
javac mypackage/HelloWorld.java
To run a class in a package, use the fully qualified name:
java mypackage.HelloWorld
Hello from my package!
You can access a class from another package by importing it using the import
keyword.
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.
java.util
, java.io
, java.lang
.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;
package
statement after imports — it must come first⬅ Previous Topic
Java null KeywordNext Topic ⮕
Java private KeywordYou 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.