1

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • @RObby What is reason behind this is not answered in that question? Difference not explained in exception. It only answers second part – fatherazrael Sep 27 '19 at 05:02
  • @RobbyCornelissen Answer - "First element to be placed on the stack itself should be the main thread. and we know how the execution control flows and its even important to note that static blocks even if they are containing variable local to their block they are never placed as an activation record on the stack but rather on the method area. so from java 7 the JVM checks for the existence of main thread record on the stack then giving the control to the static blocks after which it executes all the static blocks in its order . whereas it did the reverse in java 6 and earlier edition". True? – fatherazrael Sep 27 '19 at 06:16
  • 1
    @fatherazrael of course not. The answerer combined a lot of technical terms in an entirely nonsensical way, e.g. saying something about threads or “activation records” on the stack or local variables in the method area. Try to forget that you ever read that… – Holger Sep 27 '19 at 13:23
  • 1
    @Holger Fair enough. I linked that thing too hastily and do apologize. I will also reopen the question. Not quite sure what kind of answer OP expects though. Why did the language/VM designers decide to check for a main method first before executing static blocks? Probably just to get rid of a counter-intuitive edge case? – Robby Cornelissen Sep 27 '19 at 13:37
  • 1
    @RobbyCornelissen I suppose that’s merely the responsibility of the launcher, neither the language nor the JVM. Since it was never specified to be possible, they could change it at any point. – Holger Sep 27 '19 at 14:34

1 Answers1

0

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.

Anu Priya
  • 121
  • 2
  • 5