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.
public class Demo
{
static
{
System.out.println("First static block");
}
public Demo()
{
System.out.println("Constructor");
}
public static String staticString = "Static Variable";
static
{
System.out.println("Second static block and "+ staticString);
}
static
{
staticMethod();
System.out.println("Third static block");
}
public static void staticMethod()
{
System.out.println("Static method");
}
public static void staticMethod2()
{
System.out.println("Static method2");
}
public static void main(String[] args)
{
Demo obj = new Demo();
obj.staticMethod2();
}
}
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.
Related Posts:
- Check Java Books
- Practice BCA MCQs
- Apply for Java Internship
- Practice Programming MCQs
- Apply for Information Technology Internship