Course contentsShow
← Java
Lesson 659 of 2,87016. Packages, Imports, and JAR FilesFree lesson

Package Declaration Syntax

The package statement must be the first line (after comments) in a source file and uses dot notation.

Package Declaration Syntax

What you'll learn: How to properly declare a package at the very beginning of your Java source file.

The First Line Rule

When you create a Java source file, the package declaration must be the very first statement (ignoring comments and whitespace). This tells Java which package your class belongs to, organizing your code into a logical namespace.

The syntax is straightforward:

package com.example.myapp;

// Now class declarations follow
public class MyClass {
    // ...
}

Dot Notation for Hierarchy

Packages use dot notation to create hierarchical structures, similar to how folders contain subfolders on your computer. Each dot represents a level in the hierarchy:

package com.company.project.utils;

This creates a package structure: com → company → project → utils

Think of it like a mailing address: the package name tells Java exactly where your class "lives" in the codebase.

Comments Are Allowed First

You can place comments above the package declaration:

// This is a utility class for handling files
/* 
 * Author: John Doe
 */
package com.example.filehandler;

public class FileUtil {
    // ...
}

But once you declare a package, nothing else (except imports and class declarations) follows in the proper order.

What Happens Without a Package Declaration?

If you omit the package statement entirely, your class belongs to the default package (no name). This is only acceptable for tiny test programs or learning exercises—never in real applications.

Key Takeaway: The package statement must appear first in your source file (after comments) and uses dot notation to organize classes into hierarchical namespaces, like package com.example.myapp;