Command Palette

Search for a command to run...

Back to the lesson: Topic 14.1 — Class Loading
Core Java · Example 3 of 3

A failed static initialiser poisons the class

Only the first error names the real cause. Catching Throwable is for the demo only.

Before a class can run, a class loader finds its bytes, the JVM links it (verify, prepare, resolve) and finally initialises it by running its static initialisers, exactly once and only on first active use. A class's identity at run time is its name *plus* the loader that defined it.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that prints the loader names for Main, java.sql.Connection and java.lang.String (print bootstrap when the loader is null).

02

Demonstrate the holder idiom: print a line from the holder's static initialiser and show that it runs only when get() is first called, and only once.

03

Show that a static final String constant is inlined but a static final String computed by a method call is not.

Explain it without notes

01

Walk through what happens between new Order() executing for the first time and the constructor running.

02

What is parent delegation and why does Java use it?

03

Why can ClassCastException: com.acme.Order cannot be cast to com.acme.Order happen?

04

What is the difference between ClassNotFoundException and NoClassDefFoundError?

A failed static initialiser poisons the class
Sign in to run this example in your browser.

Expected output

attempt 1: java.lang.ExceptionInInitializerError
   message: null
   cause:   java.lang.ArithmeticException: / by zero
attempt 2: java.lang.NoClassDefFoundError
   message: Could not initialize class Main$Broken