tags:

views:

186

answers:

4

Consider the following code:-

class Name {

    {System.out.println("hi");}

    public static void main(String[] args) {
        System.out.println(waffle());
    }

    static boolean waffle() {
        try {
            return true;
        } finally {
            return false;
        }
    }
}

This never outputs "hi" . Why is this?

+24  A: 

The code in the braces is the instance initializer.

From The Java Language Specification, Third Edition, Section 8.6:

An instance initializer declared in a class is executed when an instance of the class is created (§15.9), as specified in §8.8.5.1.

If the Name class is executed, the public static void main(String[]) method is called by the Java virtual machine, but the Name class is not is not instantiated, so the code in the instance initializer will never be executed.

There is also a static initializer, which is similar in appearance to the instance initializer, but it has the static keyword in front:

static {
    // Executed when a class is first accessed.
}

Again, from The Java Language Specification, Third Edition, Section 8.7:

Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

The Initializing Fields page from The Java Tutorials also has information about the static and instance initializer blocks.

coobird
Wow, I never knew that was possible. Thanks.
Ow01
Well answered, very thorough explanation.
Zaki
+1  A: 

I think it is activated only on instance creation. Try running it as static { ... }

David Rabinowitz
+1  A: 

The block should be declared static to get it to run, i.e. static{System.out.println("hi");}

DaveJohnston
A: 

See the other answers for the explanation of the role of class (static) versus object initialization.

Consequently, the waffle() method is just distraction. The example could be:

class Name {

    {System.out.println("hello");}

    public static void main(String[] args) {
        System.out.println("world");
    }
}

This example will just print "world"; making the initializer static will print hello world.

Kaka Woef