0

Why does the part between line 2 to 4 executes first when we know that Constructor gets invoked first always ?

When I remove the curly braces from print statement between line 2 and 4, the code produces error. I know that print statement cannot be used inside class. But I wasn't able to figure out why it works when print statement is surrounded by curly braces inside a class. A detailed explanation or a reference to the answer of the problem would be amazing :) https://www.sololearn.com/post/1690816/?ref=app

27th May 2022, 5:21 AM
animus
animus - avatar
1 ответ
+ 3
Because it is wrong that the constructor comes first. In your case: { System.out.println("Instance Init"); } This block is called an instance block. It gets executed when you create an instance of your class. And it is executed before constructor. static{ } This one is a static block. It gets executed when the class is loaded and before instance block+constructor. I hope this code helps you: https://code.sololearn.com/cRKxAwr2rE6t/?ref=app Inside the comments there are some resources.
27th May 2022, 6:07 AM
Denise Roßberg
Denise Roßberg - avatar