In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading.
This is illustrated well in the following example:
One question arises from the above example:
Question: Can we execute a Java class without declaring main() method?
Answer: No since JDK 1.7 it is not possible to execute any java class without main() method. But it was one of the ways till JDK 1.6.
Output:(In JDK 1.6)
Inside Static Block.
But from JDK 1.7 onwards the above code gives an error in output.
Error: Main method not found in class staticExample, please define the main method as: public static void main(String args) or a JavaFX application class must extend javafx.application.Application
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Understanding "static" in "public static void main" in Java
- Does JVM create object of Main class (the class with main())?
- Understanding public static void main(String args) in Java
- Difference between static and non-static method in Java
- Why non-static variable cannot be referenced from a static method in Java
- Static and non static blank final variables in Java
- Difference between static and non-static variables in Java
- Understanding storage of static methods and static variables in Java
- Constructor Overloading with Static Block in Java
- How to overload and override main method in Java
- Is main method compulsory in Java?
- In Java, Can we call the main() method of a class from another class?
- What are the main differences between the Java platform and other platforms?
- Method and Block Synchronization in Java
- Valid variants of main() in Java
- GFact 48 | Overloading main() in Java
- Main thread in Java
- Replacing 'public' with 'private' in "main" in Java
- Execute main() multiple times without using any other function or condition or recursion in Java
- Static method in Interface in Java