Creating Custom Packages in Java
A custom package is declared with a package statement as the very first non-comment line of a file — package com.example.util; — and that declaration must match the actual directory structure the file lives in on disk: a class in package com.example.util needs to sit in a com/example/util folder relative to the project's source root, or the compiler won't find it correctly. Package names conventionally use reverse-domain notation, com.company.project, specifically to keep names globally distinct across different organizations' code, and follow an all-lowercase convention to visually distinguish them from class names, which are conventionally PascalCase.
Organizing code into packages beyond just avoiding naming collisions also groups genuinely related classes together logically. Package-private access, the default when no modifier is written, becomes a meaningful tool once real packages are in play, letting a package's internal helper classes stay hidden from code outside that package entirely.
The package declaration
package com.example.util; must be the very first non-comment line of the file.
Matching the directory structure
A class in package com.example.util needs to physically sit in a com/example/util folder.
Reverse-domain naming convention
com.company.project keeps package names globally distinct across different organizations.
All-lowercase convention
Package names are conventionally all-lowercase, visually distinguishing them from PascalCase class names.
Logical grouping
Packages organize genuinely related classes together, beyond just avoiding naming collisions.
package com.example.util; public class MathHelper { public static int square(int n) { return n * n; } public static void main(String[] args) { System.out.println("Square of 5: " + square(5)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.