Non Static Block

Non Static Block

  • Used to initialize non static data member.
  • Non static block execute each time when object is created.

What is the Use of Non Static block ?

  • To initialize non static data member.
Non Static block Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package block;
import thread.mainclass;
public class Nonstaticblock 
{
	//defining non static block
	{
	  System.out.println("running non static block");
	}
 
	public static void main(String[] args) 
	{
		System.out.println("main method executed");
		//craeting instance
		Nonstaticblock b1=new Nonstaticblock();
 
		//creating second instance
		Nonstaticblock b2=new Nonstaticblock();
	}
}
output:
 
main method executed
running non static block
running non static block

Static block in java

Static block

  •  Static block used initialize static data member.
  •  Static block always executed before main method.
  •  At the time of class loading jvm check for static block if present than jvm execute it.
  •  If more than one static block available than jvm execute sequentially.

What is the Use of Static block ?

  1. To initialize static data member.
  2. If you want execute something before main method then we use static block.
Static block Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package block;
public class Staticblock 
{
    //defining static block
	static
	{
	System.out.println(" 1st static block executed");	
	}
 
 
	public static void main(String[] args) 
	{
	System.out.println("main method executed");	
	}
 
	static
	{
		System.out.println("second static block executed");
	}
 
}
 
output:
1st static block executed
second static block executed
main method executed