

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When and where static blocks are executed in java?
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Example
public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
Output
Hello this is a static block This is main method
Executing a static block
JVM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.
Example
public class Sample { static { System.out.println("Hello how are you"); } }
Since the above program doesn’t have a main method, if you compile and execute it you will get an error message.
C:\Sample>javac StaticBlockExample.java C:\Sample>java StaticBlockExample Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
If you want to execute static block you need to have Main method and, static blocks of the class get executed before main method.
Example
public class StaticBlockExample { static { System.out.println("This is static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
Output
This is static block This is main method
- Related Questions & Answers
- Non static blocks in Java.
- Demonstrate static variables, methods and blocks in Java
- Static blocks in Java with example
- When can we use Synchronized blocks in Java?
- When are static objects destroyed in C++?
- What are unreachable blocks in java?
- Where are static variables stored in C/C++?
- When are static C++ class members initialized?
- When to use static methods in Java?
- What are unreachable catch blocks in Java?
- Are values returned by static method are static in java?
- What are try, catch, finally blocks in Java?
- Where and how to use static variable in swift?
- Functions that are executed before and after main() in C
- What are Orphan Blocks?
Advertisements