Skip to main content

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