Monday, 30 January 2017

STATIC BLOCK IN JAVA

When we talk about jvm we learn that jvm always first execute main() method then rest of the code. But the concept is partially correct. We can use static block which is executed when the class is loaded and before the main() method. The main purpose of static block is to initialize variables in of static type. Let us take an example –

public class Demo1 {
          static
          {
                   System.out.println("Hello static");
          }
          public static void main(String[] args)
          {
                   System.out.println("In main");
          }
          static
          {
                   System.out.println("Bye static");
          }
}

Output –
Hello static
Bye static
In main

Note – First of all , all the static blocks are executed in sequence and then the main() method is executed. And we can have n number of static blocks.

Example –
public class Demo1 {
          static String name="";
          static
          {
                   name="Rakesh";
                   System.out.println("Hello static");
          }
          public static void main(String[] args)
          {
                   System.out.println("My name is : "+name);
          }
}

Output –
Hello static
My name is : Rakesh

Note – For static variable we cannot use constructors for initialization, because constructor is only used to initialize instance variables. 

No comments:

Post a Comment