+ 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
3 Answers
+ 8
Hi, I've tried to explain it.
https://code.sololearn.com/cJYMNNHAHhlV/?ref=app
+ 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'
*/
+ 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.