Package
A package is a namespace that groups related classes. It prevents name collisions — two classes named Logger can coexist if they live in different packages. Packages are declared with the package keyword at the top of a source file.
Declaring and using
// File: src/com/example/util/StringUtils.java
package com.example.util;
public class StringUtils { ... }
// Using it from another package:
import com.example.util.StringUtils;
public class App {
public static void main(String[] args) {
StringUtils.trim(" hi ");
}
}
Package naming conventions
- Always lowercase:
com.example.util, nevercom.Example.Util. - Reverse-domain prefix: if your domain is
example.com, packages start withcom.example. - The package hierarchy maps 1:1 to directory structure on disk.
Package-private visibility
A class or member with no access modifier (no public, protected, private) is visible only within its own package. This is called package-private or default access.
Packages vs modules
Packages are Java's oldest organisation unit. Since Java 9, modules add a higher-level grouping: a module contains one or more packages and explicitly declares what it exports to other modules.