-2

I want to "execute" main() method before the static block is called. As per Java rules Static block will be executed when the class is loading and then main() method is called. Is there any way to first "execute" main method and then static block?

public class StaticDemo {
    static {
        System.out.println("in  static block");
    }

    public static void main(String  args[]){
        System.out.println("in main method");
    }
}

The output will be....

in  static block
in main method

calling main method from static block just generate expected output. but it first executed static block and from that it called main method.

import com.sun.javaws.Main;

public class StaticDemo {
        static {
        main(null);
        System.out.println("in  static block");
    }

    public static void main(String  args[]){
        System.out.println("in main method");
    }
}

The output will be...

in main method
in  static block
in main method

My expected output is....

in main method
in  static block
  • 3
    "As per Java rules Static block will be executed when the class is loading and then main() method is called" You summarized the situation perfectly well. The answer is no. Don't use a static initializer block if you don't like the behaviour. – Michael Feb 05 '19 at 13:22
  • 1
    You've answered your own question here: As per Java rules Static block will be executed when the class is loading and then main() method is called – Stultuske Feb 05 '19 at 13:22

2 Answers2

2

Is there any way to first "execute" main method and then static blk

No. There isn't. Not that static block.

Assuming that you want to execute some code after the main method has finished, you could:

  • put the code into a method that you call at the end of the main method,
  • put the code into an uncaught exception handler for the main thread and deliberately throw an exception in main(), or
  • put the code into a shutdown hook.

You could also put the code into the static block for a different class, and either dynamically load / initialize it, or trigger it in various ways. But calling a method is simpler.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Good thinking. OP might want to run some code after the app exits. If that's the intended scenario then a shutdown hook is a solution. – Adriaan Koster Feb 05 '19 at 13:31
0

It's not possible with a static block, but you could use an instance initializer block:

public class Loader {

{
    System.out.println("in instance initializer");
}

public static void main(final String[] args) {
    System.out.println("in main method");
    new Loader();
}

}

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60