Lesson Completion
Back to course

Creating Packages: Building Your Code Namespace

Beginner
10 minutes4.6Java

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.myappcom/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

  1. Must be first statement (before imports, classes)
  2. Lowercase only (convention)
  3. Reverse domain name: com.companyname.projectname
  4. Directory must match: com.myappcom/myapp/

Naming Conventions

text
com.google.guava.collect org.apache.commons.lang3 io.github.username.project

4. Interactive & Applied Code

java
// 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.class

5. The Comparison & Decision Layer

Package NamingExample
Commercialcom.company.project
Open Sourceorg.projectname or io.github.user
Educationaledu.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:

text
google.com → com.google.projectname github.io/user → io.github.user.projectname

Topics Covered

Java FundamentalsModularity

Tags

#java#packages#access-modifiers#encapsulation#scope

Last Updated

2025-02-01