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

Source File Organization Rules

Each .java file must match its directory location: com.example.Foo must be in com/example/Foo.java.

Source File Organization Rules

What you'll learn: How Java enforces that every .java file must live in a directory structure that exactly matches its package declaration.


The Core Rule

Java has a strict requirement: the location of your source file on disk must mirror its package declaration. If you declare a class in package com.example, that file must be stored in the directory path com/example/.

Specifically, if you have:

package com.example;

public class Foo {
    // class body
}

Then the file must be named Foo.java and located at:

com/example/Foo.java

The file name must match the public class name, and the directory path must match the package path, with each dot (.) in the package name corresponding to a folder separator (/ or \).


Why This Rule Exists

Java uses this convention so the compiler and runtime can find your classes. When you reference com.example.Foo, Java automatically looks in the com/example/ directory for Foo.class. This predictable mapping eliminates guesswork and makes large codebases manageable.

Think of it like a library: books are organized by category and author. If the "Mystery" section doesn't actually contain mystery books, you'll never find what you're looking for. Java's directory structure is the same — it's an organizational contract.


Example

If your project has:

src/
  com/
    example/
      Foo.java   // package com.example;
      Bar.java   // package com.example;
    other/
      Baz.java   // package com.other;

Each file's package declaration must match its folder path relative to the source root (src/).


Key Takeaway:
Every .java file must be placed in a directory structure that exactly mirrors its package declaration—com.example.Foo must live in com/example/Foo.java.