java program without main method :)

This is very unconventional but a valid code and it will run!!, the magic is the static initializer block. this block is hidden from every class by default but it executes when the class is first loaded, it prints out “Hello World” without writing a main method and the execution is stopped using System.exit() command, so preventing “main method not found” error.

public class HelloWorldWithoutMain {
    static {
        System.out.println(“Hello World!”);
        System.exit(0); // prevents “main method not found” error

Popular Posts