Skip to content

Commit da85251

Browse files
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

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed
Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
public class StaticBlock {
2-
//Class lpaded and then executed staic without main method
3-
static
4-
{
2+
//Class loaded and then executed a static without main method.
3+
static {
54
System.out.println("Block One");
65
}
76

8-
static
9-
{
7+
static {
108
System.out.println("Block Three");
119
}
1210

@@ -15,8 +13,8 @@ public static void main(String[] args) {
1513
System.out.println("Main");
1614
System.out.println("Print after the satic execuation block");
1715
}
18-
static
19-
{
16+
17+
static {
2018
System.out.println("Block Two");
2119
}
22-
}
20+
}

0 commit comments

Comments
 (0)