class W {
static int count=0;
W() {
count++;
System.out.print("c ");
}
public static void main(String[] args) {
System.out.println(new W().count+" "+new W().count);
}
}
Expected output
c 1 c 2
Actual output
c c 1 2
Why?
The actual order of things executed by the JVM is as follows:
1st W object is instantiated and its count property read.
Here the first c is send to output.
2nd W object is instantiated and its count property read.
Here the second c is send to output.
The string argument for System.out.println() is built. ( == "1 2")
The string argument is sent to the output.
Thus the output results to c c 1 2.
In this line:
System.out.println(new W().count+" "+new W().count);
The instances of W are instantiated prior to the evaluation of the rest of the statement.
The order of operations is:
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