Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 855
Szere Dyeri Avatar asked Dec 02 '08 20:12

Szere Dyeri


People also ask

What is the difference between static and non-static?

A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created. Static variables occupies less space and memory allocation happens once. A non-static variable may occupy more space.

What is static and non-static block?

The static block executes at class loading time because it can contain only static data that binds with class. So, there is no dependency on object creation. But the non-static block(Instance block) executes when the object is created. Because it can have non-static members that bind with the object.

What is the difference between static block and instance initializer block?

Static initializer block is executed when class is loaded into memory, while instance initializer block is executed when an instance of the object is created using the new() operator.

What is non-static initialization?

Java 8Object Oriented ProgrammingProgramming. Instance variables are initialized using initialization blocks. These blocks are executed when the class object is created and before the invocation of the class constructor.


2 Answers

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.

like image 74
Lawrence Dol Avatar answered Sep 22 '22 21:09

Lawrence Dol


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.

Hope this helps!

like image 33
Madan Sapkota Avatar answered Sep 20 '22 21:09

Madan Sapkota