Programming





Block in Java

Block in Java


by Administrator | 04-Apr-2020
Java

Tags:  Static Initialization Block  Instance Initialization Block  Block  Core Java

Share: 


A group of statements enclosed within curly braces can be called as a Block.  In Java, a block can be defined without a name. There can be any number of blocks in a class. The block is executed by the JVM. If there are multiple blocks of the same type then it will be executed in the order as it is available in the class.

There are two types of blocks:

  1. Static Initialization Block
  2. Instance Initialization Block                                             
  1. Static Initialization Block

A static initialization block is defined using a static modifier. This block is called automatically when a class is loaded and initialized in the memory by the JVM. It is executed only once at the time of initializing the class. It is also called a static initialization block.

Syntax

    static { 
      statements
     }

Program

public class BlockExample { 
        static{ 
               System.out.println("Instance Initialization Block."); 
        }  
        public BlockExample() { 
               System.out.println("Constructor"); 
        }  
        public static void main(String arr[]) { 
               BlockExample be1 = new BlockExample(); 
               BlockExample be2 = new BlockExample(); 
        } 
 }

Output

Initialization Block. 
 Constructor 
 Instance Initialization Block. 
 Constructor
  1. Instance Initialization Block

An instance initialization block is created without any name. Instance block will be called every time an object of a class is created. It is called after execution of the super class constructor and before execution of the current class constructor.

Syntax

    { 
      statements 
     }

Program

public class BlockExample { 
        { 
               System.out.println("Instance Initialization Block."); 
        }  
        public BlockExample() { 
               System.out.println("Constructor"); 
        }  
        public static void main(String arr[]) { 
               BlockExample be1 = new BlockExample(); 
               BlockExample be2 = new BlockExample(); 
        } 
 }

Output

Instance Initialization Block.
 Constructor 
 Instance Initialization Block. 
 Constructor

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.