Packages in Java
A package is an encapsulation mechanism used to group related classes and interfaces into a single unit.
Examples
- All database-related classes are grouped under java.sql.
- All file I/O-related classes are grouped under java.io.
Figure: package concept illustration
Advantages of Packages
- Resolve name conflicts (unique identification).
- Improve modularity and maintainability.
- Provide security for components.
Use the reverse domain name convention for package names (e.g.
com.example.project).
Figure: javac output example
Naming Convention — Example
com.icicibank.loan.housing.Account
- com.icicibank — reversed domain
- loan — module
- housing — sub-module
- Account — class
Figure: package folder structure created with
javac -d .Example Program
package com.code.java;
public class Test {
public static void main(String[] args) {
System.out.print("hello");
}
}
Compilation
Normal compilation:
javac Test.java
Using -d to generate package folders:
javac -d . Test.java
If the specified destination directory does not exist, compilation will fail with a "directory not found" error.
Figure: additional screenshot
Important Rules / Conclusion
- Only one
packagestatement is allowed at the top of a source file. - The package statement (if present) must be the first non-comment line.
- Valid file order:
package→imports→class/interface/enum.