Java - Program to demonstrate difference between Static Block and Constructor.


R.N. 07 August 2016

In this code snippet I am going to tell you difference between static block and constructor in java by example.

Static Block: Static block is a onetime execution block of java class. It executes automatically when JVM loads java class. It is useful to initialize static member's variables of class.

Constructor: It is object level one time execution block. When JVM creates object for a class then constructor of that class execute once automatically. It is useful to initialize instance members variables of object.

Java Code Snippet - Difference between Static Block and Constructor

//Declare class Bat
class Bat{
    //Constructor Block
    Bat(){
        System.out.println("Constructor of Bat");
    } 
    
    //Static Block
    static{
        System.out.println("StaticBlock of Bat");
    }
}

//Declare class Bat
class Ball{
    //Constructor Block
    Ball(){
        System.out.println("Constructor of Ball");
    } 
    
    //Static Block
    static{
        System.out.println("StaticBloack of Ball");
    }
}

public class TestDemo {
    
    //static block of TestDemo
    static{
        System.out.println("StaticBloack of TestDemo");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
          try{
            System.out.println("Main Method");
              
            //create objects of Bat class
            Bat bat  =new Bat(); 
            Bat bat1 =new Bat();
            
            //Class.forName() method load given java class into application from
            //memory without creating object of class
            Class.forName("Bat");

            Class.forName("Ball");
            Class.forName("Ball");
            
            //creating object of Ball Class
            Ball ball=new Ball();
          }
          catch(Exception E){
              E.printStackTrace();
          }
	}
}
    

We can see JVM load java classes in the following situations.

  1. When java class name given to "java tool" for execution (main () method class Load).
    e.g. >java TestDemo
  2. While creating first object of given java class.
  3. When Class.forName("class name") method is called.

    StaticBloack of TestDemo
    Main Method
    StaticBlock of Bat
    Constructor of Bat
    Constructor of Bat
    StaticBloack of Ball
    Constructor of Ball



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.