If a class contain an anonymous block having system.out.println(); [duplicate] - java

I have two classes Parent and Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
The output of the above code will be
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
Why does Java execute the code in that order? What are the rules that determine the execution order?

I learn visually, so here's a visual representation of order, as a SSCCE:
public class Example {
static {
step(1);
}
public static int step_2 = step(2);
public int step_8 = step(8);
public Example(int unused) {
super();
step(10);
}
{
step(9);
}
// Just for demonstration purposes:
public static int step(int step) {
System.out.println("Step " + step);
return step;
}
}
public class ExampleSubclass extends Example {
{
step(11);
}
public static int step_3 = step(3);
public int step_12 = step(12);
static {
step(4);
}
public ExampleSubclass(int unused) {
super(step(7));
step(13);
}
public static void main(String[] args) {
step(5);
new ExampleSubclass(step(6));
step(14);
}
}
This prints:
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14
Keep in mind that the order of the static parts matters; look back at the difference between the order of Example's static stuff and ExampleSubclass's.
Also note that the instance initialization block is always executed immediately after the super() call in the constructor (even if that call is implied/omitted), no matter the order. However, order does matter between an initialization block and a field initializer.

There are several rules in play
static blocks are always run before the object is created, so that's why you see print messages from both parents and child static blocks
now, when you are calling constructor of the subclass (child), then this constructor implicitly calls super(); before executing it's own constructor. Initialization block comes into play even before the constructor call, so that's why it is called first. So now your parent is created and the program can continue creating child class which will undergo the same process.
Explanations:
Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.

First - run child class only (comment the extend clause) to see the simple flow.
second - go to Static block vs. initializer block in Java? & read the accepted answer over there.
Edit:
Execution happens in SIC way - Static, (non static) Initializer & Constructor.
(Non static) Initializer are copied into every constructor - At the TOP! (hence lines 3/4/5/6)
Before a class is initialized, its direct superclass must be initialized - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4 (hence parent static block appears first).

Static init blocks are executed at the time of class loading.
In the class hierarchy the order for execution of static init blocks will start from top level class.
In a class the order for the execution of static block is from top to bottom.
Above rule apply regardless of where the static block is present within the class.
(In your code the parent static blocks will be executed first and then the child class static blocks.)
Instance init blocks will be executed after the call to the super(); in the constructor.
Always super(); is the very first statement in a default constructor.
In your code when you create a Child object:
The default constructor of the Child class get executed.
It will call to the super(); constructor.
Then the super class constructor is executed.
The Parent class will execute its super(); call.
After that the instance init blocks in the Parent class are executed.(From top to bottom).
Then the code within the constructor is executed (if any).
Then it will return to the Child class and execute the Child class instance init blocks.
Finally the code in the child constructor get executed (If exists).

Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static variables. It is mostly used in JDBC. Static block in java is executed every time when a class loads. This is also known as Static initialization block. Static block in java initializes when class load into memory , it means when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is preceded by static keyword.
so static block executed first.
Instance Initialization Blocks: Runs every time when the instance of the class is created.
so next Initialization block executed when instance of the class is created.
then Constructor executed

Just wanted to share my findings.
I read in one of the answers on another thread that static blocks are executed first before static fields which is not correct. It depends on which comes first, static field or static block. Have a look at below code. It will try to put things in perspective.
JVM looks for a class which has public static void main(String args[]) so that it can load that class.
It then initialises static fields of this class(if they come before static blocks). These fields can call static methods of this class or another. If they call static method of this class then that method gets served. If they call static method of another class, then static fields or blocks of that class(depending on which comes first) gets initialised first, then this method call is served.
Then, it moves to static blocks.
It comes back to main method.
class TestLab {
static int method(String a) {
System.out.println("in static method of TestLab" + " Coming from " + a);
System.out.println("b is " + b);
return 6;
}
static int a = method("Line 11");
static int b = 7;
TestLab() {
System.out.println("Inside test lab constructor");
}
static {
System.out.println("In static block of TestLab");
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("inside main method of Test 1");
int a = TestLab.method("Line 26");
}
// static Test ref=new Test();
Test1() {
System.out.println("Default Constructor of Test1");
}
{
System.out.println("In instance block of Test1");
}
static int d = TestLab.method("Line 37");
static int e = methodOfTest1();
static {
System.out.println("In Static Block of Test1");
}
static int methodOfTest1() {
System.out.println("inside static method:mehtodOfTest1()");
return 3;
}
}
Here is the output:
in static method of TestLab Coming from Line 11
b is 0
In static block of TestLab
in static method of TestLab Coming from Line 37
b is 7
inside static method:mehtodOfTest1()
In Static Block of Test1
inside main method of Test 1
in static method of TestLab Coming from Line 26
b is 7

It would be very helpful to ckeck out the object construction process with a step by step debuger, having a view in which you can see how your object is goning through the phases. I found this very useful for clearing the perspective from a higher point of view. Eclipse can help you with this with it's debugger step into function.

Here is what I found while preparing for a certification.
While we run a class, first static blocks/ static variable initialisation happens. If multiple static blocks are there, it will execute it in the order in which it appears,
Then it will execute init blocks/ instance variable initialisation.If multiple init blocks/ variable initialisation are there, it will execute it in the order in which it appears,
Afterwards it will look into the constructor.

Static block gets executed when a class is loaded into JVM. While init block gets copied into the Constructor whose object will be created and runs before creation of object.

control flow is-
static block -> Initialization block -> and finally Constructor.
static block -> This static block will be get executed only once when the control come to the class.(JVM Load this class)
Initialization block -> This Initialization block will be get executed whenever a new object Created for the Class (It will be executed from second statement of the Constructor then following constructor statements- remember First statement of the Constructor will be Super()/this())
Constructor -> This will be get whenever a new object is created.

Static init block executes at the time of class loading only ones.
Init block executes every time before creating object of the class.
Learn more with this video: Java Tutorial by Rajan Jain : Static Init Block and Init Block in java Video14 - YouTube

Related

why does this weird java code of only static blocks compile? [duplicate]

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to any function. For example following code compiles:
public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.
It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".
If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.
Uff! what is static initializer?
The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.
OK! Tell me more...
is a block of code static { ... } inside any java class. and executed by virtual machine when class is called.
No return statements are supported.
No arguments are supported.
No this or super are supported.
Hmm where can I use it?
Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.
Don't just bark! where is example?
package com.example.learnjava;
import java.util.ArrayList;
public class Fruit {
static {
System.out.println("Inside Static Initializer.");
// fruits array
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Pear");
// print fruits
for (String fruit : fruits) {
System.out.println(fruit);
}
System.out.println("End Static Initializer.\n");
}
public static void main(String[] args) {
System.out.println("Inside Main Method.");
}
}
Output???
Inside Static Initializer.
Apple
Orange
Pear
End Static Initializer.
Inside Main Method.
The static block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}
This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/
1. Execution Order
Look at the following class, do you know which one gets executed first?
public class Foo {
//instance variable initializer
String s = "abc";
//constructor
public Foo() {
System.out.println("constructor called");
}
//static initializer
static {
System.out.println("static initializer called");
}
//instance initializer
{
System.out.println("instance initializer called");
}
public static void main(String[] args) {
new Foo();
new Foo();
}
}
Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
2. How do Java instance initializer work?
The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.
Instead of
int b = 0, you could write
int b;
b = 0;
Therefore, instance initializers and instance variable initializers are pretty much the same.
3. When are instance initializers useful?
The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:
Initializer code must handle exceptions
Perform calculations that can’t be expressed with an instance variable initializer.
Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.
With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)
Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)
Thanks to Derhein.
Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.
You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..
A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.
The static initializer blocks are invoked (in the order they were defined in) when the JVM loads the class into memory, and before the main method. It's used to conditionally initialize static variables.
Similarly we have the instance initializer blocks (aka IIBs) which are invoked upon object instantiation, and they're generally used to de-duplicate constructor logic.
The order in which initializers and constructors are executed is:
Static initializer blocks;
Object initializer blocks;
Constructors;

When objects created with static reference, why do instance block & default constructor get executed before static block?

public class TestLab {
static Test aStatic=new Test();
public static void main(String[] args) {
TestLab obj=new TestLab();
}
static{
System.out.println("In static block of TestLab");
}
}
public class Test {
static Test ref=new Test();
Test()
{
System.out.println("Default Constructor of Test");
}
static
{
System.out.println("In Static Block of Test");
}
{
System.out.println("In instance block of Test");
}
}
Normally the static blocks are executed first during class loading. When the above example is executed, the following output is received:
In instance block of Test
Default Constructor of Test
In Static Block of Test
In instance block of Test
Default Constructor of Test
In static block of TestLab
Why does the instance block and Default Constructor of Test class gets executed before the static block of Test Class?
Ok. static fields / blocks are set / executed during class initialization. They are executed in the order that they appear in the code.
So, after class TestLab is loaded, when it is getting initialized, the following things happen :
static Test aStatic=new Test(); ==>
Called as part of initialization of class TestLab. From here, Test class is referenced. So, control moves to Test class.
static Test ref=new Test(); ==> i.e, first line of Test class (during its initialization phase) is executed. This line involves creating a new instance of Test, so control moves to instance block (In instance block of Test) of Test and then to constructor (Default Constructor of Test).
Now static Test ref=new Test(); is complete, so, the class initialization of Test continues and reaches the static block (In Static Block of Test). This completes initialization of Test.
Control reaches back to TestLab, now new Test() is called. So again In instance block of Test and Default Constructor of Test are printed (class is already initialized, so static fields are not initialized again and static blocks are not executed).
Control reaches static block of TestLab (In static block of TestLab).
When the type is initialized, all the static initializers and all the static field initializers are executed, in textual order. From JLS 12.4.2:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
In other words, this code gets executed:
ref = new Test();
System.out.println("In Static Block of Test");
That first line creates an instance... which requires the instance initializer to be run. All of that instance initialization happens before control returns to the type initialization part - i.e. before the line from the static initializer runs.
If you move the field declaration to after the static initializer, you'll see the opposite results.
Usually static variables/blocks will be initialized in the order they are defined, here you have marked aStatic as static. It will try to create the instance of Test by invoking constructor, but as instance block is provided it will get executed and then the constructor and eventually the static block.

java anonymous statement or what it is called?

I would like to understand what is this called. I saw this program in oracle website. I have kept breakpoint and saw this statment is called after static block and before constructor is called.
What is signifiance of this statement ?
{
System.out.print("y ");
}
In this code :
public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
static {
System.out.print("x ");
}
Its the static block and its called whenever class is loaded. In general anonymous means which does not have any name like anonymous class are clases which does not have any name and their implementation is provided right at the place where it is required and can't be reused
{
System.out.print("y ");
}
As Eran commented out ,It's an instance initialization block, and it's executed whenever an instance is created and is called even before constructor.
It is an initializer block. It is executed whenever a new instance of a class is created. Most of the time you don't really need it, because instance initialization can also be put in the constructor. The initializer block is mainly there to initialize anonymous inner classes, for which you cannot define your own constructors (because to define a constructor you need the name of the class).
This is known as a static initialization block, or static initializer.
See: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Personally, I prefer not to use them exactly for the reason stated in the documentation I sited.
There is an alternative to static blocks — you can write a private
static method: The advantage of private static methods is that they
can be reused later if you need to reinitialize the class variable.

Initialization of static method when class loads in java

I have a doubt regarding static methods. In the program written below, output will be: main. I understand this because main is a static method, so when class loads, it executes. If so, the same principle should apply for met() also, right? As it is also static. Why does only main executes whereas met() doesn't when the class loads?
public class Test {
static void met() {
System.out.println("method");
}
public static void main(String[] args) {
System.out.println("main");
}
}
No, this isn't correct.
Neither of these methods are called when the class is loaded.
main() is called when you execute the class Test.
Only static initialisers are called when the class is loaded. A static initialiser looks like this:
static
{
//code here
}
A class is loaded before the main() method is executed, and therefore its static initialiser is run before the main() method. The following snippet will make that clear.
public class TestA
{
static
{
System.out.println( "hello" );
}
public static void main( String[] args )
{
System.out.println( "bye" );
}
}
Let me explain it in detail
Types of methods There are basically two types of methods,
Instance methods
Class Methods
Instance Methods Belong to objects and you will always need an object/instance to call such methods.
static methods are the class methods and they can be called directly by class name, there is no need to have an instance of class to call them.
For example,
class Demo{
public void sayHello(){
System.out.println("Hello");
}
public static void sayHi(){
System.out.println("Hi")
}
public static void main(String args[]){
Demo.sayHi(); //Call to static/class method
Demo.sayHello(); //It will not work
Demo d = new Demo();
d.sayHello(); //It will work.
}
}
**But NONE of them gets called automatically when class loads.**
Main Difference between the two
In memory there is ONLY ONE copy of static methods which will be available for all the objects. But whenever an object is created a new copy of instance method is created for the object, so each object has its own instance method. Similar to instance & class variables.
Static methods are not meant to be run automatically, instead they are shared by all objects. Why main() method is called, because it is the entry point of the program.
Apart from them, there is static block which is called automatically only once when the class is loaded.
Example
class Main{
static{
System.out.println("static block");
}
public static void main(String args[]){
System.out.println("main");
}
}
Output will be
static block
main
main() method is not executed because it's static, it executes because it is the Entry Point for any Java program. If you want something to run, you'll need to call it from the main method. No other methods are automatically called when the class is executed.
Not at all. The main method will only run if that particular class is ran as entry point.
That met() method will not run until it has been called. The main difference it has with instance methods, is that you do not need to create an instance of the class in order to run it, you can simply run it through the class itself: Test.met();
What you mean is a static block:
private static String description;
static{
description = "this runs on loading the class";
}
You can use static block instead of static method, to print it before main method like this -
public class Test
{
static{
System.out.println("method");
}
public static void main(String[] args){
System.out.println("main");
}
}
met() is a static method, it will be in memory when the class is loaded, you need to call it.. You could use a static block to print "method".
If you want to execute on load , just intialise it as static block,
static{
System.out.println("method");
}
Because static blocks are executed once the class loads . And among other static methods main() has the high priority
No static method will get called when you call it only, you are mixing static initializer and static method
it prints main because when you run Java application it invokes main() method
there is a difference between static methods, static blocks and static variables. As you do not call the static method, it will not print
To make it print you will need to call Test.met ();
Alternatively you could have it set as a static block
as in
static {
System.out.println("static block");
}
This will be called as soon as Test is loaded.
Not all static method will be called by default when a program runs.
From Docs
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a
specified class, and invoking that class's main method. The method declaration must look like the following:
**public static void main(String args[])**
So, main will be called by JVM and someone should call met() so that it is executed.
What you understood is wrong. Because whenever class loads JVM creates Class class object and int that class class object all static methods resides. main method is entry point for JVM thats why it is executing, JVM internally calling Main method. Whenever Class loads that time it only executes Static internalization blocks.
Main() is only executed because it is the entry point.
For more information you can read the documentation.

Why do static and instance init blocks in Enums behave differently from those in Classes

In studying for the Java certification test I learned that static initialization blocks run once when the class is loaded, in order of appearance within the source code, that instance initialization blocks run each time an instance is created, and that code in constructors runs each time an instance is created after that. To test that I created a class with some static and instance init blocks and a contructor with print stuff. Everything worked as expected -- except I thought "loaded" meant just at runtime, but I guess it happens when the first instance is created, since I don't get any output at all unless I create at least 1 instance of the class. Then I tried the same with an enum and the order was all off. First, the initialization blocks run one time for each value the enum has when the enum is first referenced in code, secondly -- the init blocks marked static run after what I assumed were instance init blocks! This is the opposite of what I expected. Here is a breakdown of my questions.
Why do the init blocks marked static run last in an enum?
Can an enum have instance init blocks?
Why do the blocks I thought were instance init blocks run only once when the enum is loaded and not each time a new enum value is referenced?
Class static init blocks run when a class is "loaded". What does loaded mean? Does it occur just once when an object is instantiated in the class?
Thanks! This is very confusing to me.
public class EnumInit {
public static void main(String[] args) {
System.out.println(Color.RED.toString() + " Main");
MyInit myInit = new MyInit();
System.out.println(Color.BLUE.toString() + " Main");
MyInit mySecondInit = new MyInit();
}
}
enum Color {
RED, BLUE, GREEN;
String instanceVar = "Enum Instance Variable Text";
static { System.out.println("Enum Static init block 1"); }
{ System.out.println("Enum Instance init block 1"); }
static { System.out.println("Enum Static static init block 2"); }
Color() {
System.out.println(instanceVar);
System.out.println("Enum String Literal");
}
{ System.out.println("Enum Instance init block 2"); }
}
class MyInit {
String instanceVar = "Class Instance Variable Text";
static { System.out.println("Class Static init block 1"); }
{ System.out.println("Class Instance init block 1"); }
static { System.out.println("Class Static static init block 2"); }
MyInit() {
System.out.println(instanceVar);
System.out.println("Class String Literal");
}
{ System.out.println("Class Instance init block 2"); }
}
The Java Language Specification says this about enum constants
In addition to the members that an enum type E inherits from Enum,
for each declared enum constant with the name n, the enum type has an
implicitly declared public static final field named n of type E. These
fields are considered to be declared in the same order as the
corresponding enum constants, before any static fields explicitly
declared in the enum type. Each such field is initialized to the enum
constant that corresponds to it.
So
enum Color {
RED, BLUE, GREEN;
...
}
is actually
public static final Color RED = new Color();
public static final Color BLUE = new Color();
public static final Color GREEN = new Color();
which will get evaluated before the static blocks you have.
Why do the init blocks marked static run last in an enum?
See above.
Can an enum have instance init blocks?
Yes, compile your code and you will see.
Why do the blocks I thought were instance init blocks run only once when the enum is loaded and not each time a new enum value is referenced?
Enum constants are created (instantiated) once the enum type is initialized. You don't create a new enum any time you do
Color color = Color.RED;
You are just referencing an already created, existing object.
Class static init blocks run when a class is "loaded". What does loaded mean? Does it occur just once when an object is instantiated in the class?
When a class is referenced in the JVM for the first time, it is loaded by the ClassLoader and initialized. Read more about it here.
In enum the static init block is executed last.
Enums
1st - instance init block
2nd - constructor block
last - static init block or any other declared static (only once and will be always last executed)
Classes
1st - static init block or any other declared static (only once, always first to be executed)
2nd - instance init block
3rd - constructor

Categories