Wednesday, May 18, 2016

Static Block vs Constructor


Static Block can be called once on class instantiation whereas constructor get called on every new
object instantiation.



public class Sample {
static{ //Static block can be called once
System.out.println("Static block is called");
}
Sample(){//Constructor called at any number of times
System.out.println("Constructor is called");
}
void method(){
System.out.println("Method is called");
}
static void display() {
   System.out.println("Static method is called");
 }
public static void main(String args[]){
Sample s=new Sample();
Sample s2=new Sample();
s.method();
System.out.println("Main method called");
display();
}
}

Output 

Static block is called
Constructor is called
Constructor is called
Method is called
Main method called
Static method is called