JAVA โ€ข FUNCTIONS AND PROGRAM STRUCTURE

Packages & Naming Conventions โ€” Create and use packages; apply package naming conventions

Learn how Java packages organize code into logical groups and why naming conventions keep large projects manageable.

Historical Context & Motivation

As software projects grew from a few hundred lines to millions of lines of code throughout the 1980s and 1990s, developers faced a serious organizational problem. Imagine writing a school essay where every paragraph, heading, and footnote lived in a single document with no folders or file structure โ€” finding anything would become nearly impossible. Early programming languages like C let you group code into separate files, but there was no built-in system for preventing two files from accidentally using the same name. When James Gosling and the team at Sun Microsystems designed Java in the mid-1990s, they solved this problem by building packages directly into the language.

1991
Project Green Begins
James Gosling starts developing what would become Java at Sun Microsystems, initially targeting embedded devices. The need for organized, portable code is clear from the start.
1995
Java 1.0 Released
Java launches with a built-in package system. The standard library ships with packages like java.lang and java.io, demonstrating the convention of grouping related classes together.
1998
Java 2 & Enterprise Growth
Java 2 introduces hundreds of new classes. The reverse-domain naming convention (e.g., com.sun.java) becomes standard to prevent naming conflicts across organizations worldwide.
2017
Java 9 Module System
Java 9 adds the module system (Project Jigsaw), building on top of packages to provide even stronger organization for very large applications.

The central question that packages answer is straightforward: How do you organize thousands of classes so that names don't collide and developers can find what they need? This lesson will teach you how to create packages, import classes from them, and follow the naming conventions that professional Java developers use every day.

Core Principles & Definitions

A package in Java is a named group of related classes and interfaces that provides a separate namespace โ€” a way to guarantee that class names don't conflict. Think of a package like a folder on your computer. You can have a file called notes.txt in your English folder and another notes.txt in your History folder without any confusion, because the folder path makes each file unique. Packages work the same way for Java classes.

1

Namespace Separation

Packages let two different classes share the same simple name without conflict. A Date class in java.util is entirely separate from a Date class in java.sql.
2

Logical Organization

Related classes are grouped together, making it easy to find functionality. For instance, all input/output classes live in java.io.
3

Access Control

Packages work with Java's access modifiers. Classes with default (package-private) access are only visible to other classes in the same package, providing a layer of encapsulation.
4

Reverse-Domain Convention

Professional packages start with a reversed internet domain name (e.g., com.google.maps) to ensure global uniqueness.
โœฆ KEY TAKEAWAY
Think of packages like the address system for houses. Your street name alone isn't unique across the world, but your full address โ€” country, state, city, street, house number โ€” is. Similarly, com.myschool.projects.Calculator uniquely identifies your Calculator class even if a thousand other developers also wrote one. The package is the "full address" that makes each class name globally unique.

Visual Explanation โ€” Package Hierarchy

The left panel shows the folder (directory) structure on disk, while the right panel shows the corresponding package declaration at the top of each Java file. Notice that com.myschool.math maps to the folder path com/myschool/math/.

The diagram above reveals the most important rule of Java packages: the package name must exactly match the folder path where the source file lives. If you declare package com.myschool.math; at the top of a file, that file must be saved inside the folder com/myschool/math/. If there is a mismatch, the Java compiler will throw an error. This tight coupling between folders and packages is what keeps large codebases navigable.

โš ๏ธ Important Rule
The package statement must be the very first line of code in your Java file (comments and blank lines above it are fine). Only one package declaration is allowed per file, and every class in that file belongs to that package.

How Packages Work โ€” Syntax & Import Statements

Declaring a Package

Every Java source file can begin with a package declaration, which tells the compiler which package the file belongs to. The syntax is simple:

PACKAGE DECLARATION SYNTAX
package <domain>.<organization>.<project>.<module>;
Each segment is separated by a dot, uses only lowercase letters, and matches a folder in the file system. For example: package com.myschool.math;

Importing Classes from Other Packages

When you want to use a class from a different package, you have three options. The most common is the import statement, which appears after the package declaration and before the class definition. You can import a single class or use a wildcard to import all classes from a package.

SINGLE-CLASS IMPORT
import com.myschool.math.Calculator;
Imports only the Calculator class. This is the preferred style because it makes dependencies explicit.
WILDCARD IMPORT
import com.myschool.math.*;
Imports all classes in the com.myschool.math package. Convenient but can make it harder to see which classes are actually being used.
FULLY QUALIFIED NAME (NO IMPORT NEEDED)
com.myschool.math.Calculator calc = new com.myschool.math.Calculator();
You can always use the full package path directly in code. This is useful when two imported packages contain classes with the same name, such as java.util.Date and java.sql.Date.
๐Ÿ’ก Free Package
The java.lang package is automatically imported into every Java program. That's why you can use String, System, Math, and other fundamental classes without writing an import statement.

Package Naming Conventions in Detail

Java's naming conventions aren't enforced by the compiler โ€” you won't get an error for using uppercase letters in a package name. However, following these conventions is considered essential in professional development because they prevent naming collisions and make code instantly readable to other developers. The key convention is the reverse internet domain name pattern.

This diagram breaks down the four segments of a typical package name: the reversed top-level domain, the organization, the project, and the specific module. The green checkmarks and red crosses at the bottom summarize the key naming rules.
Common package naming conventions with examples
ConventionGood ExampleBad Example
All lowercasecom.myschool.mathCom.MySchool.Math
Reverse domain nameorg.apache.commonscommons.apache.org
No hyphens (use underscores)com.my_school.appcom.my-school.app
Avoid Java keywordscom.example.my_intcom.example.int
Meaningful namescom.school.gradebookcom.school.stuff

Worked Example โ€” Building a School Project with Packages

Let's walk through creating a complete project that uses packages. Imagine you're building a grade calculator application for your school. You want to separate the math logic from the user interface code.

Creating a Multi-Package School Project
1
Step 1 โ€” Plan Your Package StructureDecide how to organize your classes. We'll create two packages: com.school.grades.logic for calculation classes and com.school.grades.ui for the user interface. This means we need two sets of folders.
Folder structure: src/com/school/grades/logic/ and src/com/school/grades/ui/
2
Step 2 โ€” Create the GradeCalculator ClassCreate a file called GradeCalculator.java inside src/com/school/grades/logic/. The first line must declare the package:
package com.school.grades.logic; public class GradeCalculator { public double average(double[] scores) { double sum = 0; for (double s : scores) { sum += s; } return sum / scores.length; } }
3
Step 3 โ€” Create the Main Application ClassCreate App.java inside src/com/school/grades/ui/. This class needs to import GradeCalculator from the other package:
package com.school.grades.ui; import com.school.grades.logic.GradeCalculator; public class App { public static void main(String[] args) { GradeCalculator calc = new GradeCalculator(); double[] scores = {92, 85, 78, 96, 88}; System.out.println("Average: " + calc.average(scores)); } }
4
Step 4 โ€” Compile from the Source RootNavigate to the src directory and compile both files. The compiler needs to be able to find all referenced packages from this root directory.
javac com/school/grades/logic/GradeCalculator.java javac com/school/grades/ui/App.java
5
Step 5 โ€” Run the ApplicationRun the program using the fully qualified class name (the package name plus the class name). Java uses this to locate the correct .class file.
java com.school.grades.ui.App Output: Average: 87.8

Package Types โ€” Built-in vs. User-Defined

Java packages fall into two broad categories. The built-in packages ship with the Java Development Kit (JDK) and provide ready-made functionality. The user-defined packages are the ones you create yourself to organize your own code. Understanding both types is essential for writing well-structured Java programs.

Comparison of built-in and user-defined Java packages
FeatureBuilt-in PackagesUser-Defined Packages
SourceIncluded with the JDKCreated by the developer
Examplesjava.util, java.io, java.langcom.school.grades, org.club.roster
Import needed?Yes (except java.lang)Yes, when accessing from other packages
NamingStarts with java. or javax.Starts with reversed domain (e.g., com.)
PurposeStandard functionality: data structures, I/O, networkingCustom application logic specific to your project
โœฆ KEY TAKEAWAY
Built-in packages are like the apps that come pre-installed on a new phone โ€” they're there from the start and cover the basics. User-defined packages are like the apps you download and install yourself to handle your specific needs. Both follow the same rules, but you control the organization and naming of user-defined packages.

Connection to Modules and Advanced Organization

Packages are the foundation of code organization in Java, but as applications scale to millions of lines, even packages can become difficult to manage. Java 9 introduced the module system (also called Project Jigsaw), which groups related packages together into a higher-level unit. Think of it this way: if packages are folders, modules are like labeled boxes that hold multiple folders and explicitly list which folders are visible to the outside world.

Packages vs. Modules in Java
ConceptPackageModule (Java 9+)
GranularityGroups related classesGroups related packages
Defined bypackage declaration in each filemodule-info.java descriptor file
Access controlPackage-private (default) or publicExports specific packages; hides internal ones
Required to learn first?Yes โ€” fundamentalNo โ€” typically covered in advanced courses

For now, focus on mastering packages. Once you're comfortable with them, modules will feel like a natural extension. The good news is that packages you create today will work perfectly inside modules later โ€” nothing about the package system changes when modules are added on top.

Practice Problems

PROBLEM 1 โ€” CONCEPTUAL
Explain why two different Java classes can both be named Timer without causing a conflict, as long as they are in different packages. What mechanism makes this possible?
PROBLEM 2 โ€” BASIC CALCULATION
A student's website domain is coolprojects.org. They are building a chess game with separate packages for the board logic and the AI. Write the correct package declarations and the folder paths (from the source root) for a class called Board.java in the board package and MoveGenerator.java in the AI package.
PROBLEM 3 โ€” INTERMEDIATE
The following code produces a compile error. Identify the two mistakes and write the corrected version. import com.school.utils.StringHelper; package com.school.app; public class Main { public static void main(String[] args) { StringHelper helper = new StringHelper(); } }
PROBLEM 4 โ€” APPLIED
You are building a library management system. You need classes for Book, Member, Checkout, DatabaseConnection, and SearchService. Your school's domain is lincoln-high.edu. Design a package structure by grouping related classes, writing the package name for each group, and explaining why you chose that grouping.
PROBLEM 5 โ€” CRITICAL THINKING
Java allows you to use a wildcard import like import java.util.*; to bring in all classes from a package. However, most professional style guides (like Google's Java Style Guide) discourage wildcard imports. What problems could wildcard imports cause, especially as a project grows? Consider what happens when a new class is added to a package you're wildcard-importing.

Lesson Summary

Java packages are named groups of related classes that provide namespace separation, logical organization, and access control. Every package name must match its folder path on disk, and the package declaration must be the first line of code in each Java file. To use classes from other packages, you write import statements โ€” either single-class imports (preferred) or wildcard imports.

The standard naming convention uses a reversed internet domain name followed by project and module segments, all in lowercase letters separated by dots (e.g., com.myschool.math). Built-in packages like java.util and java.io ship with the JDK, while user-defined packages let you organize your own code. As projects grow, Java 9's module system adds an additional layer above packages for even larger-scale organization.

Varsity Tutors โ€ข Java โ€ข Packages & Naming Conventions