When writing a Java program, it's not just your syntax that matters — the structure of your source file plays a critical role in how your code compiles and runs. Let's explore the most important rules Java developers must follow when declaring and organizing a .java
file.
📌 1. File Naming and Extensions
Every Java source file must end with the .java
extension.
Example:
HelloWorld.java
You can name the file anything as long as there is no public class inside it. However, if a source file contains a public class, the file name must match the class name exactly (including case).
✅ Correct:
public class Main {}
// File name: Main.java
❌ Incorrect:
public class Main {}
// File name: Test.java → Compilation Error
👥 2. Number of Classes per File
You can define multiple classes, interfaces, enums, or annotations in a single .java
file. However:
- Only one public type is allowed per file.
- Each non-public type can have any name, and the compiler will still generate separate
.class
files for each.
class Animal {}
class Dog {}
public class Main {}
// Must be saved as Main.java
🚀 3. The Role of the Main Method
Any class (public or not) can contain a public static void main(String[] args)
method.
During execution:
java ClassName
- The JVM looks for the class specified in the command and checks if it contains a valid
main()
method. - If found, it executes it. If not, you'll get an error.
🛠️ 4. Compilation Behavior
When compiling your file using:
javac FileName.java
Java performs the following steps:
- Syntax Check: All code is validated for syntax errors. If any are found, no
.class
files are generated. - Type-by-Type Validation: If syntax is fine, each declared type is checked in order.
- Class File Generation: If a type is valid, a
.class
file is created for it.
To see what's happening during compilation, use:
javac -verbose FileName.java
This shows you every class file being loaded and compiled.
📦 5. Package and Import Declarations
- A
package
statement, if used, must be the first line of the source file. import
statements come next.- Class, interface, or enum declarations follow.
✅ Order of declarations:
package com.example;
import java.util.*;
public class Main { ... }
You can have any number of import statements, and both package
and import
declarations apply to all types declared in the file.
🧠 Final Thoughts
Understanding source file structure isn’t just academic — it’s essential for building real-world Java projects, working with IDEs, or preparing for interviews. These rules ensure your Java code is portable, maintainable, and error-free during compilation.
💡 Pro Tip: Even seasoned Java developers run into simple compilation issues due to naming mismatches or misplaced public classes. Stick to the rules — and your builds will thank you.