Thursday 27 July 2017

java diff between constructor and static block

Q. what is difference between  constructor and static block ? 
Ans-------> 



Constructor is a object level one time execution block . Constructor executes automatically when object is created. We place logic to initialize an instance variable in the constructor.

Static block is class level one time execution block. It executes automatically when JVM loads the java class.
We place logic to initialize static variables is the static block.

USAGE: if we want to open connection to file only for one time for all objects then place that logic in static block.


eg.
DemoApp.java

class test{
static{
System.out.println("Test : static block");
}
public Test(){
System.out.println("Test : 0 para constructor");
}



class Demo{
static{
    System.out.println("Demo static block");
 }
public Demo{
System.out.println("Demo : 0 para constructor");
 }
}


public class DemoApp{
static{
 System.out.println("DempApp : ststic block");
}

public static void main(String adc[])throws Exception
{
  System.out.println("DemoApp main()");
Test t1=new Test();
Test t2=new Test();

Class.forName("Demo");
Class.forName("Demo");
}
}



\\output
DemoApp : static block
DemoApp main()
Test 0 para constructor
Test 0 para constructor
Demo static block

No comments:

Post a Comment