Course contentsShow
← Java
Lesson 18 of 2,8701. Java Setup and First ProgramFree lesson

Source File and Class Name Matching

Understanding the requirement that public class names must match the filename and the .java extension.

Source File and Class Name Matching

What you'll learn: Why your Java filename must exactly match your public class name.

When you write Java code, you're not free to name your files whatever you like—Java enforces a strict naming rule that connects your code to your file system.

The Core Rule

If you declare a public class in Java, the filename must exactly match the class name, plus the .java extension.

For example, if you write:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

You must save this file as HelloWorld.java. Not helloworld.java, not Hello.java, not MyProgram.java—it must be an exact match, including capitalization.

Why This Rule Exists

Think of Java files like labeled boxes in a warehouse. When the compiler (javac) needs to find a class, it looks for a box (file) with the exact label (name). If the label doesn't match what's inside, the compiler gets confused and cannot organize your code properly.

This rule helps Java:

  • Locate classes quickly across large projects
  • Organize compiled .class files predictably
  • Prevent naming conflicts

What Happens If You Break the Rule?

If your public class name is Calculator but you save it as Math.java, the compiler will reject it with an error message indicating the class name doesn't match the filename.

Important Detail

You can only have one public class per .java file, and that class name must match the filename. This keeps your code organized and predictable.

Key Takeaway: Your public class name and filename (minus .java) must be identical—case-sensitive, character-for-character—or your code won't compile.