1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: Creating a package requires: (1) package declaration as the first line in your Java file, (2) matching directory structure (com.myapp → com/myapp/), and (3) following naming conventions (lowercase, reverse domain). The package statement tells Java which namespace the class belongs to.
Think of mailing addresses. Just as "123 Main St, Springfield, IL" uniquely identifies a house, com.myapp.User uniquely identifies your class globally!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy: The Apartment Address
An apartment address has:
- Country (com/org)
- City (company name)
- Building (project)
- Unit (module)
Same structure as Java packages!
3. Technical Mastery (The "Deep Dive")
Package Declaration Rules
- Must be first statement (before imports, classes)
- Lowercase only (convention)
- Reverse domain name:
com.companyname.projectname - Directory must match:
com.myapp→com/myapp/
Naming Conventions
com.google.guava.collect
org.apache.commons.lang3
io.github.username.project4. Interactive & Applied Code
// File: src/com/myapp/model/User.java
package com.myapp.model; // MUST be first!
public class User {
private String name;
}
// Compile:
// javac -d bin src/com/myapp/model/User.java
// Creates: bin/com/myapp/model/User.class5. The Comparison & Decision Layer
| Package Naming | Example |
|---|---|
| Commercial | com.company.project |
| Open Source | org.projectname or io.github.user |
| Educational | edu.university.course |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question:
"What happens if package declaration doesn't match directory structure?"
Answer: Compile error or runtime ClassNotFoundException! The JVM searches for com.myapp.User in com/myapp/User.class. If the file is elsewhere, it fails.
Pro-Tip: Use your domain in reverse:
google.com → com.google.projectname
github.io/user → io.github.user.projectname