Issue
in a file named filename.java
class filename{
public static void main(String[] a){
System.out.println("From filename main method");
}
}
public class ClassName{
public static void main(String[] a){
System.out.println("From First main method");
}
}
Observe below commands:
Command 1:
C:\javaDJ>java filename.java
From filename main method
Command 2:
C:\javaDJ>javac filename.java
filename.java:7: error: class ClassName is public, should be declared in a file named ClassName.java
public class ClassName{
^
1 error
Observation:
command 1 compiles (i assume internally ) and executes successfully.
command 2 throws compilation error.
Problem Statement :
How is java cmd able to compile the file called filename.java, when the file(filename.java) contains a public class (ClassName)which is not named 'filename.java' (the name of the file-name.) ?
Solution
To highlight a specific section from the JEP#Launch Single-File Source-Code Programs with regards to the behavior
In source-file mode, execution proceeds as follows:
- 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.
Answered By - Naman
Answer Checked By - Pedro (JavaFixing Volunteer)