Q:

Weird behavior of println() method in Java

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?

A:

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:

Instantiate first new W(), causing c to be printed
Evaluate first new W().count
Instantiate second new W(), causing c to be printed
Evaluate second new W().count
Concatenate the result and print.

A:

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.

