code block without any method signature

java

Solution

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

- Set fields to default initial values (`0`, `false`, `null`)

- Call the constructor for the object (but don't execute the body of the constructor yet)

- Invoke the constructor of the superclass

- Initialize fields using initializers and initialization blocks

- 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.

Problem

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?

Original source

Related problems