How to Get Differences Between Static Block and Constructor in Java


Here this example show us how to get differences between static block and constructor in Java.

Source Code

package com.beginner.examples;

public class StaticVSConstructorExample {
	//Static block will be called first than constructor.
	//Static block will be called only once. 
    static {
        System.out.println("static block");
    }
     
    public StaticVSConstructorExample(){
        System.out.println("constructor");
    }
     
    public static void main(String[] args){
        StaticVSConstructorExample s1 = new StaticVSConstructorExample();
        StaticVSConstructorExample s2 = new StaticVSConstructorExample();
        StaticVSConstructorExample s3 = new StaticVSConstructorExample();
    }
}

Output:

static block
constructor
constructor
constructor
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments