As software grows in size, organizing hundreds of source files into logical namespaces is critical. In Java, Packages provide directory-based namespace encapsulation, while the Java Platform Module System (JPMS) provides modular boundaries across packages.
To assign a class to a package, place the package statement at the very top of the .java file:
// Must be the first non-comment line in the source file:
package com.veewom.banking.services;
public class TransactionService {
public void processTransfer() {
System.out.println("Processing bank transfer...");
}
}
To use a class residing in another package, import it explicitly:
// Explicit Single Class Import (Recommended for clarity):
import com.veewom.banking.services.TransactionService;
// Wildcard Package Import (Imports all classes in package):
import java.util.*;
public class AppLauncher {
public static void main(String[] args) {
TransactionService service = new TransactionService();
service.processTransfer();
}
}
JPMS enforces Strong Encapsulation. Even if a class is declared public, it is completely hidden from external modules unless its package is explicitly exported in module-info.java:
// module-info.java (Root of module source directory)
module com.veewom.banking {
// Requires dependent modules
requires java.sql;
requires org.apache.commons.lang3;
// Exports specific packages to consumers
exports com.veewom.banking.services;
exports com.veewom.banking.models;
}
Exam Question: "Which package in Java is imported automatically into every source file without an explicit import statement?"
Answer: java.lang! The Java compiler automatically imports java.lang.* into every single Java file. This is why fundamental classes like System, String, Math, Thread, Object, and Integer can be used without any import statements.
Now let us explore modern Java Records—the concise, immutable data carriers introduced in Java 16+. Proceed to: Java Record Classes (Java 16+) →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Package-private default access.
Package declaration rules.
Packaging modern data records.
Configuring CLASSPATH.