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

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

Leave a Reply