Anatomy of a Java Source File
You'll learn: How a .java file is organized and the basic rules that govern its structure.
What's Inside a Java Source File?
Think of a Java source file like a labeled filing cabinet. The cabinet itself has a specific name on the outside, and inside it holds organized content. A .java file works the same way—it's a text file that contains your Java code, structured according to strict naming and organizational rules.
The Basic Structure
Every Java source file contains at least one class declaration. A class is a blueprint for creating objects (you'll learn more about that later), but for now, just know it's the fundamental building block of Java code.
Here's what you need to know:
File Naming Rules
- The file name must exactly match the class name inside it
- It must end with
.java - Java is case-sensitive:
MyProgram.javais different frommyprogram.java
Class Declaration
The basic syntax looks like this pattern (in words): the word "public," then "class," then the name you chose, followed by curly braces that contain the class's content.
Why These Rules Matter
When you use javac (the compiler tool you learned about), it expects this structure. If your file is named Hello.java, the compiler looks for a class named Hello inside. Mismatch these, and compilation fails.
The Filing Cabinet Analogy
- File name = the label on the cabinet's exterior
- Class name = the main section divider inside
- Curly braces
{}= the cabinet's walls that hold everything together
Key Takeaway: A Java source file must be named identically to its public class name, end in .java, and follow Java's case-sensitive syntax conventions—this structure allows the JDK tools to find and compile your code correctly.