java - Static block execution before main method -
this question has answer here:
- static initializer in java 9 answers
does static block of class execute before main method of same class?
example:
public class example { static { system.out.println("hi"); } public static void main(string[] args) { system.out.println("bye"); } }
the output of program :
hi
bye
my doubt why output not:
bye
java run static intializers of class before method called (or instance created). jls, section 12.4.1, states:
a class or interface type t initialized before first occurrence of 1 of following:
t class , instance of t created.
a static method declared t invoked.
a static field declared t assigned.
a static field declared t used , field not constant variable (§4.12.4).
t top level class (§7.6) , assert statement (§14.10) lexically nested within t (§8.1.3) executed.
part of initialization order is:
- next, execute either class variable initializers , static initializers of class, or field initializers of interface, in textual order, though single block.
therefore, static initializer run first, , "hi" printed; main
called print "bye".
Comments
Post a Comment