2

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);
    }
}
MWiesner
  • 8,868
  • 11
  • 36
  • 70

1 Answers1

4

I can only reproduce the behavior when using java StaticBlockPrint.java but then, in all versions since JDK-11.

When I compile with javac and run with java 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

class Initializer {
    public static void main(String... arg) {
        ClassLoader cl = Initializer.class.getClassLoader();

        // variant 1
        try {
            cl.loadClass("A").getMethod("main");
        }
        catch(Throwable t) {
            System.out.println("A: " + t);
        }

        // variant 2
        try {
            Class.forName("B", true, cl).getMethod("main");
        }
        catch(Throwable t) {
            System.out.println("B: " + t);
        }
    }
}
class A {
    static {
        System.out.println("A initialized");
    }
}
class B {
    static {
        System.out.println("B initialized");
    }
}
A: java.lang.NoSuchMethodException: A.main()
B initialized
B: java.lang.NoSuchMethodException: B.main()
Holger
  • 285,553
  • 42
  • 434
  • 765