Commit da85251
committed
feat: Demonstrate multiple static blocks execution order in Java
WHAT the code does:
- Defines class StaticBlock with three static initialization blocks and a main method.
- Static blocks:
- Print "Block One", "Block Three", and "Block Two".
- Execute automatically when the class is loaded, before main().
- main():
- Creates an instance of Test (another class, assumed defined elsewhere).
- Prints "Main".
- Prints "Print after the satic execuation block".
WHY this matters:
- Shows that **multiple static blocks** are allowed in a Java class.
- They are executed **in the order they appear in the source code**, not alphabetically or by name.
- Reinforces that static blocks run **once at class loading**, before the main method is invoked.
- Useful for complex static initializations, configuration loading, or setting up resources before program execution.
HOW it works:
1. JVM loads StaticBlock class.
2. Executes static blocks top to bottom:
- Prints "Block One".
- Prints "Block Three".
- Prints "Block Two".
3. Executes main():
- Instantiates Test (if its static block exists, that will execute once at Test’s class loading).
- Prints "Main".
- Prints "Print after the satic execuation block".
Tips and gotchas:
- You can have multiple static blocks, but prefer combining into one for clarity unless separation improves readability.
- Static blocks execute once per classloader lifecycle; re-running requires reloading the class.
- Be cautious with complex logic in static blocks—failures here can prevent class loading altogether.
- For constants and simple static initializations, inline initialization (`static int X = 42;`) is clearer.
Use-cases / analogies:
- Think of static blocks like "pre-show setup" before the actual program (main) begins.
- Example: loading configuration files, initializing loggers, registering drivers (e.g., JDBC driver registration historically used static blocks).
Short key: java-static-block execution-order classloading initialization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 0664a60 commit da85251
1 file changed
+6
-8
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
4 | | - | |
| 2 | + | |
| 3 | + | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
8 | | - | |
9 | | - | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
12 | 10 | | |
| |||
15 | 13 | | |
16 | 14 | | |
17 | 15 | | |
18 | | - | |
19 | | - | |
| 16 | + | |
| 17 | + | |
20 | 18 | | |
21 | 19 | | |
22 | | - | |
| 20 | + | |
0 commit comments