+ 6

Confused by the output of this Java code

I came across a question in a Java quiz. Its answer/output confused me because it didn't seem like things were printed in the correct order. If someone could explain why "hey1yo!" is the correct output, I'd be very happy. Thank you. https://code.sololearn.com/cZ4Pp2vj21J6/?ref=app

24th Jun 2019, 10:02 PM
Lizinlectual
Lizinlectual - avatar
3 Antworten
+ 8
24th Jun 2019, 11:12 PM
voja
voja - avatar
+ 1
public class SoloTest { static { System.out.println("1. 'static initialization block'"); } // ------------- { System.out.println("2. constructor a, 'initializer block'"); } // ------------- SoloTest() { System.out.println("3. constructor b"); } public static void main(String[] args) { new SoloTest(); } } /* output: 1. 'static initialization block' 2. constructor a, 'initializer block' 3. constructor b */ /* if you comment line: //new SoloTest(); constructor doesn't run output: 1. 'static initialization block' */
25th Jun 2019, 2:05 AM
zemiak
+ 1
About static and instance blocks: https://code.sololearn.com/cRKxAwr2rE6t/?ref=app First: static block: print hey Second: First Instance block: print a //at this time a = 1 Second Instance block: a = 7 //you can add a print statement inside this block to see it Third: Constructor: print yo In your main method you are creating an object: -> the class is loaded -> call static block -> instance blocks executes when an object is created -> calls the constructor See what happens if you create another object.
25th Jun 2019, 6:01 PM
Denise Roßberg
Denise Roßberg - avatar