i am using Static block without using main method in java version "18.0.2" 2022-07-19 the code is perfectly working without any compile error and runtime error how is this possible?
class StaticBlockPrint{
static {
System.out.println("Hello world!");
int i = 8;
i =i+8;
System.out.println(i);
System.exit(0);
}
}
I can only reproduce the behavior when using
java StaticBlockPrint.javabut then, in all versions since JDK-11.When I compile with
javacand run withjava StaticBlockPrint, all versions since Java 7, including 18.0.2.1, consistently produce an error regarding the missing main method.Technically, the difference is tiny. The class initializer ends with
System.exit(0);, so when it is executed before the missing main method is about to be reported, the process is terminated without an error message.The following program demonstrates two variants of how a launcher could be implemented