Java Enum why static line executes only once? [duplicate] - java

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 4 years ago.
The result is:
1
3
1
3
1
3
2
The constructor runs for A,B and for C (3 times). But if you use static keyword it runs only once. What is the reason of this? And why does this line executes last?
enum Enums {
A, B, C;
{
System.out.println(1);
}
static {
System.out.println(2);
}
private Enums() {
System.out.println(3);
}
}
public class MainClass{
public static void main(String[] args) {
Enum en = Enums.C;
}
}

There are three different things at play here:
private Enums()
{
System.out.println(3);
}
This is the constructor. It (or some other potential constructor) runs when an instance is created.
{
System.out.println(1);
}
This is an instance initializer. It runs when an object is being constructed, regardless of which constructor is used.
static
{
System.out.println(2);
}
This is a static initializer. It gets run once this class has been loaded into the JVM, whether or not an instance is being created. However, since we're dealing with an enum, all its instances have to be created as part of loading the class. That's why it runs after the three constructors and initializers.

To complement #smallhacker answer you should read the answers in Static initializer in Java
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.

Related

Why is the static initializer not executed if referenced static field is final [duplicate]

This question already has answers here:
Static block in Java not executed
(5 answers)
Closed 8 years ago.
class a
{
static final int a =5;
static {
System.out.println("hi");
}
}
class b
{
public static void main(String[] args) {
System.out.println(a.a);
}
}
Why doesn't the static block run,and the output is only
5
whereas if I remove final keyword from the class variable, the static block gets executed and the output becomes
hi
5
Basically what happened is that the static final combination on primitives and Strings cause them to be inlined by the compiler, and this might have prevented the static initialization block from execution, since a class is never loaded by the classloader, as a.a was resolved during compilation
Because your variables with the keywords static final are compiled-time constants which do not trigger the loading of the class containing the field.
Try putting running this code with static final on the variable a
System.out.println(a.a)
a var = new a();
as you can see the output will be
5
hi
The static block isnt triggered when a is called but the moment an instance of the class is created it gets triggered. It can be triggered by any of these:
an instance of the class is created,
a static method of the class is invoked,
a static field of the class is assigned,
a non-constant static field is used, or
for a top-level class, an assert statement lexically nested within the class is executed.
A question very similar to yours which might be helpful:
Static block in Java not executed

static initialization block vs constructor java [duplicate]

This question already has answers here:
In what order do static/instance initializer blocks in Java run?
(8 answers)
Closed 9 years ago.
class prog
{
static
{
System.out.println("s1");
}
prog()
{
System.out.println("s2");
}
public static void main(String...args)
{
prog p = new prog();
}
}
Output is
s1
s2
As per the output, it seems that static initialization block gets executed before the default constructor itself is executed.
What is the rationale behind this?
Static block executed once at the time of class-loading & initialisation by JVM and constructor is called at the every time of creating instance of that class.
If you change your code -
public static void main(String...args){
prog p = new prog();
prog p = new prog();
}
you'll get output -
s1 // static block execution on class loading time
s2 // 1st Object constructor
s2 // 2nd object constructor
Which clarifies more.
Strictly speaking, static initializers are executed, when the class is initialized.
Class loading is a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it is possible to load a class without initializing it (for example by using the three-argument Class.forName() variant).
No matter which way you approach it: a class will always be fully initialized at the time you create an instance of it, so the static block will already have been run at that time.
That is right static initialization is being done when class is loaded by class loader and constructor when new instance is created
Static block one time execution block..
it executes while class loading..
when object is created for a class constructor executes..

What is the use of {} block in Java [duplicate]

This question already has answers here:
Java independent block of code [duplicate]
(2 answers)
Calling a Java method with no name
(8 answers)
Closed 9 years ago.
Hello Friends what is the use of having just a block in Java class
public class StaticExample {
{
System.out.println("I m here...");
}
}
That's an initialization block. It gets executed when a new instance is created. If you think that that's a job for the constructor, it is a place where you can put code that is executed no matter which constructor is used. They are executed in the order they appear, before the constructor. If you put static in front of an initialization block, it becomes a static initialization block, which is executed as soon as the class is loaded.
It's called an initializer block and is invoked every time an instance of the class is created.
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
The code is invoked before the code in the constructor and doesnt depend on the latter.
public class InitializerExample {
public InitializerExample() {
System.out.println("InitializerExample");
}
{
System.out.println("I'm here...");
}
public static void main(String[] args) {
new InitializerExample();
}
}
will produce
I'm here...
InitializerExample
It is documented in the official tutorial here

Which will be loaded first static variable or static block? [duplicate]

This question already has answers here:
Java : in what order are static final fields initialized?
(5 answers)
Closed 9 years ago.
One of my friends asked me that which will load first static variable or static block.
My answer points to static variable.
So he gave me two equations and said to differentiate between them
First Equation
public class Some {
public static void main(String args[])
{
System.out.println(Some.x);
}
static {
System.out.println(Some.x);
}
static int x=90;
}
O/P: 0 90
Second Equation
public class Some {
public static void main(String args[])
{
System.out.println(Some.x);
}
static int x=90;
static {
System.out.println(Some.x);
}
}
O/P: 90 90
I tried to decompile the byte code and found it's same for both the above equation.
Please help me to differentiate between them.
I am confused when the static variable will initialised.
Static blocks are initialised in the order they appear in the source file.
There are several questions relating to this on stack overflow already...
This one has a good answer for you: Java : in what order are static final fields initialized?
static variables and static blocks are executed in an order in which they appear.
Here first O/P: 0 90 as in the System.out.println(Some.x); statement of the static block executed after the static variable initialization statement static int x=90;
static Variables are executed when the JVM loads the Class, and the Class gets loaded when either its been instantiated or its static method is being called.
static Initializer Block gets Initialized before the Class gets instantiated or before its static method is called, and Even before its static variable is used.
I am giving a simple example for control flow of static and instance stuffs:
Suppose you have 2 clases A and B.
class A extends to class B. and class B has a main method. After successful compilation of both your command on cmd is like:
java B
Now what will happen see step by step:
classes A and B will be loaded
static members and blocks of class A will be identified and will be
executed sequentially(one by one)(But only once at the time of class loading)
static members and blocks of class B will be identified and executed(one by one)(But only once at the time of class loading)
main method of class B will be invoked(In case class B don't have a main method then class A's main method will be invoked)
As soon as you will create an object of class A : all instance
members initialization and instance block execution will be done in
class A
the constructor of class A(which you used for creating object) will
be executed
If you create an object of class B: all instance
members initialization and instance block execution will be done in
class A.
the constructor of class A(default constructor or any other if you called it from B's constructor) will
be executed
then all instance
members initialization and instance block execution will be done in
class B
and after that the constructor of class B(which you used for
creating object) will be executed
Note: static members and blocks execution is done only one time while loading class for first time, while instance members and instance blocks are executed each time as we create an object of the class.
Please let me know if I am not correct.

Java: Strange static method head definition (expression instead of return type) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static Initialization Blocks
Unusual “static” method declaration
I'm trying to prepare for a OCJPC in the near future, and I came across a construct I had never seen before. As it is tough to google for programming constructs, I am asking the question here. The code fragment:
class Geryon {
static { System.out.print("a"); }
{ System.out.print("b"); }
Geryon(String s) { System.out.print(s); }
public static void main(String[] args) {
new Geryon("c");
}
}
I am referring to the 2 print statements inside theGeryon() method header in the place where I would expect a return type. As far as I was able to google, a static method header consists of:
access-modifier keyword-"static" return-type|void method-name
Judging from the answer to the quiz question, the code does not only compile, but will also be run. Can anyone direct me to a source where this is explained?
A is a static initializer that gets called when the class is initialized by classloader, this :
static { System.out.print("a"); }
And the other (B) is an anonymous block that gets called every time the class is instantiated :
{ System.out.print("b"); }
Oh and the third print statement, C, is just a normal constructor call.
You will get all three lines if you instantiated one Geryon, like the code you posted. But then the next time you instantiated a Geryon you will only get two - B and C; as it has already been initialized by classloader, so the static block does not get called.

Categories

Resources