Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 316
Hablu Avatar asked Mar 15 '13 08:03

Hablu


People also ask

Which will execute first static block or static variable?

There is an order in which static block/method/variable gets initialized. Static Blocks are called even before the main method which is nothing but a static method i.e. execution point of every class.

Are static variables initialized first?

Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn't need any object.

Which is executed first static block or instance block?

Order of execution When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.

Why static method is executed first?

Because the Java Language Specification mandates that static blocks must be executed first. There can be more than one static block and each of them are executed in the order of their declaration. Static blocks are executed when the class in loaded in memory(JVM).


1 Answers

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?

like image 169
James Avatar answered Sep 24 '22 01:09

James