Non static blocks in Java.


A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Example

 Live Demo

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

Output

Hello this is a static block
This is main method

Instance initialization blocks

Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors.

Whenever you define an initialization block Java copies its code to the constructors. Therefore you can also use these to share code between the constructors of a class.

Example

 Live Demo

public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

Output

25
Krishna

In a class, you can also have multiple initialization blocks.

Example

 Live Demo

public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   {
      System.out.println("Initialization block");
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

Output

Initialization block
25
Krishna

You can also define an instance initialization block in the parent class.

Example

public class Student extends Demo {
   String name;
   int age;
   {
      System.out.println("Initialization block of the sub class");
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}

Output

Initialization block of the super class
Initialization block of the sub class
25
Krishna

Updated on: 06-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements