Wisdom of Helios

Static Block in JAVA

4 Comments

Static blocks are blocks defined within the body of a class using the static keyword. A static block is executed when the JVM loads the class. The static block will execute ONLY at the FIRST TIME the class is loaded to the JVM.
Let us explore a very simple example.

public class SampleStatic
{
  static int x = 100;
  static int y;

  static
    {
      y = x*5;
      System.out.println(y);
     }
}

Output: 500
So when you will run this code snippet you will get the output 500. Because when the class is first loaded the static block will execute first and print the 500 to the output stream.

Now , I’m going to elaborate something about the static block –
1. The static block will execute ONLY at the FIRST TIME the class is loaded to the JVM.
2. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. But when executing the static blocks will execute in order to the source file. JRE is responsible for making this order. After the serial is done JVM will account these static blocks as a single static blocks and execute them.

public class StaticExmple1 {

String str = null;
StaticExmple1(String s)
{
str = s;
}
static String strString = null;
static{

System.out.println("First Static block");
}
static {
System.out.println("Second Static block");
}

Output: First Static block
Second Static block

3.  As static method and variable static block is also uses ONLY static variable and data.

4.  Inside the Static block you can ONLY declare non-static variables.

5.  Static block  / Static blocks can not be inherited.

6.  If  you declare a static variable after the last static block then no static block can access this static variable and a compile-time error will occur.

7.   You cannot return a value  from  a static block. Inside a static block you can not use this and super keyword. Static block cannot throw an exception.

Now, I’m going to demonstrate an example that will contain all characteristics of  a static block.

public class StaticExmple1 {
String str = null;
StaticExmple1(String s)
{
str = s;
}
static String strString = null;
static{

System.out.println("First Static block");
}
static {
System.out.println("Second Static block");
}
static String staticMethod()
{
strString = "Static Method";
return strString;

}
static {
String s ="";
s = staticMethod();
System.out.println(s);

}
public static void main(String[] args)
{
StaticExmple1 se1 = new StaticExmple1("First Object");
System.out.println(se1.str);

StaticExmple1 se2 = new StaticExmple1("Second Object");
System.out.println(se2.str);
}
}

Output: First Static block
Second Static block
Static Method
First Object
Second Object

This code snippet is self-explained  🙂 .

Advantages of  static block

1. The primary use of static initializers blocks are to do various bits of initializations that may not be appropriate inside a constructor.

2.  If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.   (In one of my job training the trainer told us to run a Java code without a main method. I simply wrote a static block and inside this block I printed a “Hello World” message ……… It worked …….. 😛  😀 ).

3.  Security related issues or logging related tasks.

 

 

[This portion is copied from JustForTechies  Blog . I’m grateful to them]

Again if you miss to precede the block with “static” keyword, the block is called “constructor block” and will be executed when the class is instantiated. The constructor block will be copied into each constructor of the class. Say for example you have four parameterized constructors, then four copies of contructor blocks will be placed inside the constructor, one for each. Lets execute the below example and see the output.

public class ConstructorBlockExample{

    {
        System.out.println("This is first constructor block");
    }

    public ConstructorBlockExample(){
        System.out.println("This is no parameter constructor");
    }

    public ConstructorBlockExample(String param1){
        System.out.println("This is single parameter constructor");
    }

    public ConstructorBlockExample(String param1, String param2){
        System.out.println("This is two parameters constructor");
    }

    {
        System.out.println("This is second constructor block");
    }

    public static void main(String[] args){
        ConstructorBlockExample constrBlockEx =
		             new ConstructorBlockExample();
        ConstructorBlockExample constrBlockEx1 =
		             new ConstructorBlockExample("param1");
        ConstructorBlockExample constrBlockEx2 =
		             new ConstructorBlockExample("param1", "param2");
    }
}

Output:   This is no parameter constructor

This is first constructor block

This is second constructor block

This is single parameter constructor

This is first constructor block

This is second constructor block

This is second parameter constructor

This is first constructor block

This is second constructor block

The above example is self-explanatory.  🙂

Author: Munir

I'm good for nothing

4 thoughts on “Static Block in JAVA

  1. Nice article. Informative and helpful.

  2. hey man.. superb article.. very helpful.. 🙂

  3. without main method the above programs are wrong….where is System.exit(0)

Leave a comment