Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior of println() method in Java

Tags:

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?

like image 950
Jatin Tamboli Avatar asked Sep 24 '13 08:09

Jatin Tamboli


2 Answers

The actual order of things executed by the JVM is as follows:

  1. 1st W object is instantiated and its count property read.

    Here the first c is send to output.

  2. 2nd W object is instantiated and its count property read.

    Here the second c is send to output.

  3. The string argument for System.out.println() is built. ( == "1 2")

  4. The string argument is sent to the output.

Thus the output results to c c 1 2.

like image 163
Sirko Avatar answered Oct 10 '22 02:10

Sirko


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:

  1. Instantiate first new W(), causing c to be printed
  2. Evaluate first new W().count
  3. Instantiate second new W(), causing c to be printed
  4. Evaluate second new W().count
  5. Concatenate the result and print.
like image 40
Kevin Bowersox Avatar answered Oct 10 '22 00:10

Kevin Bowersox