Skip to main content

Command Palette

Search for a command to run...

Java Source File Declaration Rules

Updated
4 min read
Java Source File Declaration Rules

A Java source file has specific rules that must be followed for its structure, naming, and declaration to ensure correct compilation and execution.

File Naming Rules

  1. The Java source file name must match the public class name (if a public class exists).

    • Correct:

        public class HelloWorld { }
      
    • Incorrect:

        public class Test { }
      

      File name: HelloWorld.java (Mismatch, will cause an error)

  2. Java source file must have the .java extension.

Package Declaration Rules

  1. If the file belongs to a package, the package statement must be the first statement in the file.

    • Correct:

        package com.example;
        public class MyClass { }
      
    • Incorrect:

        public class MyClass { }
        package com.example;  // Compilation Error: Package statement must be first
      

Import Statement Rules

  1. Imports must be placed after the package declaration (if any) and before the class declaration.

    • Correct:

        package mypackage;
        import java.util.Scanner;
      
        public class MyClass { }
      
    • Incorrect:

        import java.util.Scanner;
        package mypackage;  // ❌ Compilation Error: Package statement must come first
      
    • Wildcard imports (*) are allowed but not recommended for efficiency.

    • Correct:

        javaCopyEditimport java.util.*;  // Imports all classes in java.util
      
    • Bad Practice:

        javaCopyEditimport java.util.ArrayList;
        import java.util.List;
      
    • Instead, use:

        javaCopyEditimport java.util.*;
      

Class Declaration Rules

  1. A Java file can have multiple classes, but only one public class.

    • Correct:

        javaCopyEditpublic class Main { } // Public class (must match filename)
        class Helper { } // Non-public class
      
    • Incorrect:

        javaCopyEditpublic class Main { }
        public class Helper { }  // ❌ Compilation Error: Only one public class allowed
      
  2. If a public class exists, the file name must match the public class name.

    • File: Main.java

        public class Main { }
      

      File: Helper.java

        public class Main { }  // ❌ Compilation Error: Filename must be "Main.java"
      

Method Declaration Rules

  1. The main method must be inside a class.

    • Correct:

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

        public static void main(String[] args) {  // ❌ Compilation Error: No enclosing class
            System.out.println("Hello, World!");
        }
      
  2. The main method must have the exact signature.

    • Correct:

        public static void main(String[] args) { }
      
    • Incorrect:

        static void main(String[] args) { }  // ❌ Compilation Error: Must be public
      

Interface and Enum Declaration Rules

  1. A Java file can contain multiple interfaces and enums.
  • Correct:

      javaCopyEditinterface MyInterface { }
      interface AnotherInterface { }
    
  • Enums can also be declared within a file:

      javaCopyEditenum Status { ACTIVE, INACTIVE }
    
  1. A Java file can contain a mix of classes, interfaces, and enums.
  • Example:

      javaCopyEditpublic class MyClass { }
      interface MyInterface { }
      enum MyEnum { ONE, TWO }
    

Access Modifiers in Java Files

ModifierApplicable toScope
publicClasses, Methods, VariablesAccessible from anywhere
privateMethods, VariablesAccessible only within the class
protectedMethods, VariablesAccessible within the package & subclasses
No Modifier (default)Classes, Methods, VariablesAccessible only within the package

Java Source File Structure (Best Practice)

Correct Java Source File Order

javaCopyEdit// 1️⃣ Package declaration (optional)
package com.example;

// 2️⃣ Import statements (if needed)
import java.util.*;

// 3️⃣ Public class declaration (if required)
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

// 4️⃣ Other classes, interfaces, enums (if needed)
class Helper { }
interface MyInterface { }
enum Status { ACTIVE, INACTIVE }

Special Cases

❓ Can we have a Java file without a class?

  • No, Java requires at least one class.

  • Example (Invalid)

      javaCopyEditSystem.out.println("Hello, World!");  // ❌ Compilation Error: Not inside a class
    

Summary: Java Source File Declaration Rules

RuleDescription
File Name RuleMust match the public class name (if any).
Package RuleMust be the first statement in the file (if present).
Import RuleMust be placed after the package and before the class.
Class RuleOnly one public class per file, but multiple non-public classes are allowed.
Method RuleThe main method must have public static void main(String[] args).
Interface/Enum RuleMultiple interfaces and enums are allowed.
Access Modifier RuleOnly public and default (package-private) classes are allowed at the top level.

More from this blog

Naveen P.N's Tech Blog

94 posts

Java File Declaration Guidelines