In Java, a package is a namespace that groups related classes and interfaces together. Packages help organize large projects, avoid naming conflicts, and improve code reusability and maintenance.
A package is declared using the package keyword at the very top of a Java source file.
// Declaring a package named com.example.util
package com.example.util;
public class Helper {
public void greet() {
System.out.println("Hello from Helper class");
}
}
Change the names below to see how Java Packages map to Folders.
// Using a class from another package
import com.example.util.Helper;
public class MainApp {
public static void main(String[] args) {
Helper h = new Helper();
h.greet();
}
}
Hello from Helper class
The Helper class is accessed using its package name. The import statement allows us to use the class without writing the full package path every time.
import