The java version used is as follows:
java 17.0.3 2022-04-19 LTS
Java(TM) SE Runtime Environment (build 17.0.3+8-LTS-111)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.3+8-LTS-111, mixed mode, sharing)
The class is named: Test2.java (contents are as follows:)
import java.util.Random;
public class B {
public static final void main(String[] args) {
System.out.println(new Random().nextInt(10));
}
}
public class T2 {
public static void main(String[] args) {
System.out.println("This from another function");
}
}
Confusion:
Following commands run quite differently when trying to compile or run the class:
- With
java Test2.javathe result comes of as a random integer (as the code says). - With
javac Test2.javathe compilation fails. This is what I was expecting in the first place for the command 1. But, it did not happen that way.
Thought process:
In all of my experience I've learned that there should be only one public top level class and that public class's name should be same as the file name. In this case the Test2.java file should contain a class called Test2. But I deliberately created two top level public classes none of them containing the class name as of the file's.
Actual question: Why command1 runs and finds whatever first class's main method was and prints that statement although it shouldn't have compiled in the first place. Command2 works as expected. Why the discrepancy?
class fileversion here. When you run command1 (from my example) you do not produce a .class file. When you do javac (command2) the .class file will be produced once the compilation was successful. I am sorry but your answer is not helpful.