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?
Where am I?
.That block called as instance initialization block. When the object is created in Java, there is an order to initialize the object.
0
, false
, null
)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With