Executing the single code java file using java Vs javac using jdk11



I am using JDK11. Below is my sample class –

public class SayHi {
    public static void main(String[] args) {
        System.out.println("Hi There");
    } 
} 

I executed the above class with command “java filename.java” for below scenarios

ColumnA -> Class declared as public? ColumnB -> File name same as class name?

ColumnA ColumnB Result
  Yes      Yes   Yes
  No       Yes   Yes
 *Yes      No    Yes
  No       No    Yes

For all the scenarios, the command executed successfully and I got the result. I get compile-time error for the “Yes-No” case, if I run the “javac” command on the file name.

  1. Why I am not getting the compile-time error when I am executing “java” command on the file name?

  2. I have multiple public classes in a single code file. I am able to execute the file using “java filename.java” command. What I am missing with the compile-time issues when running the file with “java” command. Please help me on this.

Answer

The answers to all your questions can be found in JEP 330. I believe the following excerpts provide answers to your questions.

the first class found in the source file is executed

The source file should contain one or more top-level classes, the first of which is taken as the class to be executed

The compiler does not enforce the optional restriction defined at the end of JLS ยง7.6, that a type in a named package should exist in a file whose name is composed from the type name followed by the .java extension

In other words, when you compile a java source code file with javac, the source code file must contain a single, “public” class whose name matches the name of the file. But when you run a java source code file using the java command, the above restriction does not apply.

The class to be executed is the first top-level class found in the source file. It must contain a declaration of the standard public static void main(String[]) method.



Source: stackoverflow