Tuesday, June 23, 2009

Reason me out!!

Code:
public
class Foo {
public Foo() { System.out.println("constructor called"); }

static { System.out.println("static initializer called"); }

{ System.out.println("instance initializer called"); }
}

Execute :
new Foo();
new Foo();

Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called

--Varun

3 comments:

  1. These are called as instance initializers. The code within these blocks are copied into every constructor by the compiler and are used to share common code across overloaded constructors.

    http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

    ReplyDelete
  2. Exactly!! :-) Just came to know about this today!!

    ReplyDelete
  3. that is because static blocks are always called once when the class is loaded into the memory by JVM which is not the case with instance and constructor initializers.

    ReplyDelete