Java Program to Check Whether Which One is Executed First, Static Block or the Static Method

This is a Java Program to Check Whether Which One is Executed First , Static block or the Static Method.

Static block is used to initialise the static data members dynamically. If you want to perform a task only once in life cycle of class then put that code in static block.

Here is the source code of the Java Program to Check Whether Which One is Executed First , Static block or the Static Method. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Demo
  2. {   
  3.     static 
  4.     {
  5.         System.out.println("First static block");
  6.     }
  7.  
  8.     public Demo()
  9.     {
  10.         System.out.println("Constructor");
  11.     }
  12.  
  13.     public static String staticString = "Static Variable";
  14.  
  15.     static 
  16.     {
  17.         System.out.println("Second static block and "+ staticString);
  18.     }
  19.     static 
  20.     {
  21.         staticMethod();
  22.         System.out.println("Third static block");
  23.     }
  24.  
  25.     public static void staticMethod() 
  26. 	{
  27.         System.out.println("Static method");
  28.     }
  29.  
  30.     public static void staticMethod2() 
  31. 	{
  32.         System.out.println("Static method2");
  33.     }
  34.     public static void main(String[] args)
  35.     {
  36.         Demo obj = new Demo();
  37.         obj.staticMethod2();
  38.     }    
  39. }

Output:

$ javac Demo.java
$ java Demo
 
First static block
Second static block and Static Variable
Static method
Third static block
Constructor
Static method2

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.