What is the difference between a static and a non-static initialization code block

difference between static variable and static method in java
difference between static and non static in java
how to access non static variable in static method java
static block in java
static variables java
difference between static and non static data members in c++
static method in java with example
difference between static and instance variable

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.

Static block vs. initializer block in Java?, static block {} 1. static blocks are used to initialize the static data in the class, it creates We cannot write static blocks inside a static method and non-static method A static block, or a static initializer, is a section of code which is run when the  Static and non static blank final variables in Java. A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block.

What is a difference between static block and static method in java , Every methods in java are non-static method, but the methods must not have static keyword Below are the various important differences among these: calling GFG.geek();. filter_none. edit close. play_arrow. link brightness_4 code Difference between Static and Shared libraries · Initialize a static Map using Java 9  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

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");
    }
}

Difference between static and non-static method in Java , The Local variables and Instance variables are together called Non-Static variables. See here; static block and static variables are executed in order they are present in a program. filter_none. edit close. play_arrow. link brightness_4 code  1. Static block is also known as a static initialization block whereas instance block is also known as instance initialization block or non-static block. 2. They execute before the instance block whereas instance block executes after the static blocks. 3.

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:

  1. Initializer code must handle exceptions
  2. 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.

Difference between static and non-static variables in Java , To define a static initialization block we use the keyword static, while no keyword Let's discuss more differences between static initialization block and instance As we can see in the code, the static initialization block was called as soon as  To be a bit more precise, compile-time constants held in static final variables are initialized by the JVM before the static initializer code is run, whereas non-static final fields might also hold compile-time constants but are initialized by the constructor like ordinary instance fields. However, you will need Reflection to notice the difference as any ordinary reference to such a field will be replaced by the constant value at compile-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.

Static Initialiation Block vs Instance Initialization Block- Decodejava , In general, do not use non-static initializer blocks (and maybe avoid static about initializer blocks in case you see them in legacy code, or they come up on a  The non-static block: Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Should I use initializer blocks in Java?, Static block is used for initializing the static variables. As you can see in the output that the non-static variable is different for both the objects but the static  Static initialization block is used to initialize class variables, which are defined with static keyword. You can define a static initialization block in your class and it is automatically called when your class loads, i.e. when you run your program. Note : Static initialization block precedes with the keyword static.

Java, This is the fundamental difference between static (class) variables Compiling the code below will result in an error: Unlike local variables, static fields and methods are NOT thread safe in The static modifier can also be specified in a static block, better known as a " static initialization block ", which is  Non-static variables can’t be accessed with in a Java static block. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are executed in the sequence that they appear in the source code.

10 things you need to know about the static modifier in , What is the difference between static and instance blocks? So, a static block similarly contains code that executes only one time no matter how Double brace initialization is using the instance blocks in the anonymous  Initialization blocks run in the same order in which they appear in the program. Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. // Java code to illustrate order of. // execution of constructors, static.

Comments
  • The static initializer is actually invoked later, when the class is initialized, after it has been loaded and linked. That happens when you instantiate an object of a class or access a static variable or method on the class. In fact if you have a class with a static initializer and a method public static void staticMethod(){}, if you execute TestStatic.class.getMethod("staticMethod");. The static initializer won't be invoked. More info here docs.oracle.com/javase/specs/jvms/se10/html/…
  • @Totò: Yes, that's what the resolution of the class entails (at least they used to refer to it as link+init as "resolution" way back when). I am not surprised you can use reflection to discover things about a class without it resolving.
  • Thanks Madan! Can static block be used instead of afterPropertiesSet() of InitializingBean?
  • Yes, you can! Static initializer become called when the class gets loaded by the jvm. So its the really first phase where code gets executed. If you have a constructor too, the order would be: static initializer, constructor, afterPropertiesSet
  • Nope, no explicit way to invoke it, the class initializer is never represented by a Method instance but only invoked by the Java virtual machine.
  • As a follow up, if I do not create an instance of the object but instead I call a public static function. Does it imply that this block is guaranteed to execute before this public function call? Thanks.
  • If you call a public static function of the class, then the class needs to be loaded first, so yes, the static initializer will execute first.
  • Unless it was class initialisation which (indirectly) called the code which is trying to use it. IFYSWIM. Circular dependencies and all that.
  • @Tom is right - it's possible to write something where one static initializer calls a static method before another static initializer is called, but my mind recoils at the thought so I never considered it.
  • Thanks a lot to you both for the clarification.