Why static block is not getting executed (if I do not use main() method)?

479 Views Asked by At

Following is my program:

public class Statico {
    static{
        System.out.println("Rarara");
        System.exit(0);
    }
}

When I compile and run program using Java 6:

C:\D>"c:\Program Files\Java\jdk1.6.0_19\bin\java" Statico
Rarara //Output is displayed

It does not say that it needs Main() (i.e Exception in thread "main" java.lang.NoSuchMethodError: main) is not thrown as we are using System.exit(0)

However, when I execute above code in Java 8, we always get exception:

C:\D>"c:\Program Files\Java\jdk1.8.0_141\bin\java.exe" Statico
Error: Main method not found in class Statico, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

What is reason behind this?

Can we achieve Java 6 type functionality as shown above in Java 8 too?

If yes, how?

1

There are 1 best solutions below

0
Anu Priya On

static block execution without main method is only supported in Java versions 1.6 and below. Above that its not supported, main method is required.