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
.classfiles 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
.classfiles 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
.classfile 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
packagestatement, if used, must be the first line of the source file. importstatements 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.