6

I have a java class as follows:

public class MyClass {

    public MyClass() {
        System.out.println("In Constuctor.");
    }

    {
        System.out.println("Where am I?");
    }

    public static void main(String[] args) {
        new MyClass();
    }
}

Output of above class is:

Where am I?
In Constuctor.

I have few questions regarding the block which prints Where am I?

  • Why didn't it shows any error/warning?
  • What is the meaning of block which prints Where am I?.
  • Why that block gets executed before constructor?
  • If it's valid syntax then what is the use of it?
Bhushan
  • 6,151
  • 13
  • 58
  • 91
  • 4
    It is an [instance initializer](http://stackoverflow.com/questions/1355810/how-is-an-instance-initializer-different-from-a-constructor). – Jesper Feb 07 '14 at 11:54
  • 2
    Official documentation is at http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html – Qwerky Feb 07 '14 at 12:01
  • It was enough to just scan the *Related Questions* which this site was offering you while you were writing the question. See it on the sidebar to the right: [Loose blocks of code](http://stackoverflow.com/questions/20916650/loose-blocks-of-code?rq=1) – Marko Topolnik Feb 07 '14 at 12:01

1 Answers1

11

That block called as instance initialization block. When the object is created in Java, there is an order to initialize the object.

  1. Set fields to default initial values (0, false, null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet)
  3. Invoke the constructor of the superclass
  4. Initialize fields using initializers and initialization blocks
  5. Execute the body of the constructor

For more details, look here and JLS 8.6

If it's valid syntax then what is the use of it?

Instant initializers used to initialize the instance variables. You can use the instance initializer when declaring an anonymous class.

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

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105