Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code block without any method signature

Tags:

java

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?
like image 995
Bhushan Avatar asked Jan 12 '23 06:01

Bhushan


1 Answers

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.

like image 129
Abimaran Kugathasan Avatar answered Jan 21 '23 13:01

Abimaran Kugathasan