// File 1: smo_1.java
public class smo_1 {
static {
System.out.println("I am static");
}
int my_add(int x, int y) {
return x + y;
}
}
// File 2: smo_main.java
public class smo_main {
public static void main(String[] args) throws Exception {
Class.forName("smo_1"); // Loads smo_1 and executes its static block WITHOUT an object!
int x = 5, y = 16;
smo_1 obj1 = new smo_1();
System.out.println(obj1.my_add(x, y));
}
}Output:
I am static
21
| Method Signature | Runs static { }? |
Behavior |
|---|---|---|
Class.forName(String className) |
Yes (Immediately) | Loads the class by its fully qualified name and runs its static block. |
Class.forName(String name, boolean init, ClassLoader cl) |
Configurable (init) |
If init == false, loads the class without running static { } yet. |
Calling Class.forName("smo_1") by itself forces the JVM ClassLoader to load and initialize smo_1, executing static { System.out.println("I am static"); } without ever calling new smo_1():
public class StaticBlockWithoutObject {
public static void main(String[] args) throws ClassNotFoundException {
// Executes smo_1's static { ... } block without calling 'new smo_1()':
Class<?> loaded = Class.forName("smo_1");
System.out.println("Loaded class metadata: " + loaded.getSimpleName());
}
}Terminal Output:
I am static
Loaded class metadata: smo_1
A class's static { ... } block executes only once when the class is first initialized in memory. Whether Class.forName("smo_1") runs first or new smo_1() runs first, whichever statement touches smo_1 first triggers "I am static", and subsequent calls do not repeat it:
public class StaticBlockRunsOnce {
public static void main(String[] args) throws Exception {
System.out.println("1. Calling Class.forName("smo_1")...");
Class.forName("smo_1"); // Triggers static block here (1st time smo_1 is initialized)
System.out.println("2. Calling new smo_1()...");
smo_1 obj1 = new smo_1(); // Does NOT re-run static block!
System.out.println("Sum: " + obj1.my_add(5, 16));
}
}Terminal Output:
1. Calling Class.forName("smo_1")...
I am static
2. Calling new smo_1()...
Sum: 21
If you want to inspect a class's metadata without triggering its static initializer block yet, pass false as the second argument to the 3-parameter overload:
public class LazyLoadWithoutInit {
public static void main(String[] args) throws Exception {
ClassLoader loader = LazyLoadWithoutInit.class.getClassLoader();
// initialize = false loads bytecode WITHOUT running static { ... } yet:
Class<?> c = Class.forName("smo_1", false, loader);
System.out.println("Class loaded with initialize=false (static block not run yet)");
// First active use (newInstance) now triggers the static block:
c.getDeclaredConstructor().newInstance();
}
}Terminal Output:
Class loaded with initialize=false (static block not run yet)
I am static
Once Class.forName("smo_1") returns the Class<?> object, you can create an instance and invoke my_add(5, 16) dynamically even if the class name came from a configuration file:
import java.lang.reflect.Method;
public class DynamicMethodInvoke {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("smo_1");
Object instance = clazz.getDeclaredConstructor().newInstance();
Method addMethod = clazz.getDeclaredMethod("my_add", int.class, int.class);
Object result = addMethod.invoke(instance, 5, 16);
System.out.println("Reflective my_add(5, 16) = " + result);
}
}Terminal Output:
I am static
Reflective my_add(5, 16) = 21
| Block Type | Syntax | How Many Times? | When Executed |
|---|---|---|---|
| Static Initializer | static { ... } |
Once per class | When class is first initialized (forName or 1st use). |
| Instance Initializer | { ... } |
Once per object | Every time new is called, right before constructor body. |
| Constructor | smo_1() { ... } |
Once per object | Every time new smo_1() is called. |
Because the string passed to Class.forName(...) is only resolved at runtime, the compiler requires either declaring throws Exception / throws ClassNotFoundException or wrapping the call in a try-catch block:
public class SafeForNameLoader {
public static void main(String[] args) {
try {
Class.forName("com.plus2net.NonExistentPlugin");
} catch (ClassNotFoundException e) {
System.out.println("Caught ClassNotFoundException: " + e.getMessage());
}
}
}Terminal Output:
Caught ClassNotFoundException: com.plus2net.NonExistentPlugin
Class.forName() always requires the fully qualified class name! If smo_1 has package Pack1; at the top of its file, calling Class.forName("smo_1") throws a ClassNotFoundException—even if smo_main is in the exact same package! You must pass Class.forName("Pack1.smo_1").
If an uncaught runtime exception occurs inside static { ... } during Class.forName(), the JVM wraps it in an ExceptionInInitializerError and marks the class as permanently unusable for the rest of the program run.
public class OopExample2FullDemo {
static int initCount = 0;
static { initCount++; }
public static void main(String[] args) throws Exception {
Class.forName("OopExample2FullDemo");
Class.forName("OopExample2FullDemo");
if (initCount == 1) {
System.out.println("All Java Class.forName() & static block checks passed! initCount=1");
}
}
}Terminal Output:
All Java Class.forName() & static block checks passed! initCount=1
MySQL's JDBC driver class contains a static { DriverManager.registerDriver(new Driver()); } block. Calling Class.forName() executes that static block to register the driver (see Java MySQL Connection Tutorial).
Class.forName("smo_1") resolves a runtime String name and immediately runs the static block, whereas the class literal smo_1.class is checked at compile time and does not trigger the static block until a static member or constructor is accessed.
Yes. If a class defines several static blocks, the Java compiler merges and executes them in top-to-bottom source file order when the class is initialized.
clazz.newInstance() bypassed checked exception checking. Modern Java uses clazz.getDeclaredConstructor().newInstance() instead.
No, not directly, because no object instance exists when the static block runs. It can only access static fields or instantiate an object inside the block first.
smo_main.java and smo_1.java.Class.forName() with JDBC drivers.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.