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.

advertisement
  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

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

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!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn