Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Why the following code print out "BAC", instead of "ABC"?

Tags:

java

tostring

Please help me understand this code. I am new to java.

// C.java
class C { 
  public static void main(String arg[]) { 
    System.out.println("A"+new C()); 
  } 
  public String toString() { 
    System.out.print("B"); 
    return "C"; 
  } 
}
// output:
// BAC  
like image 676
dennis Avatar asked Aug 01 '11 02:08

dennis


3 Answers

The evaluation goes something like:

Call println("A" + new C())
Since new C() hasn't been computed yet, we need to compute it, so...
Compute new C().toString()
    Print "B"
Print line with "A" + "C"

As you can see, the order of the print statements is "B", "A", "C"

like image 70
Mark Elliot Avatar answered Oct 23 '22 03:10

Mark Elliot


You need understand 2 concepts here: Java left-to-right evaluation rule and side effect.

"A"+new C()

following the same rule. It gets "A" first, which is a String literal, put it somewhere. Then it evaluate

new C() 

it construct a C Object first, then invoke toString() method of C Object, and gets the value of C object, which is "C", then concatenates "A" and "C" together, and println "AC".

Inside the toString() method of C Object, there is a System.out.print("B"); which is invoked when Java evaluate the above expression. It is printed out before the evaluation completed.
That is why "B" is printed first

like image 41
Saurabh Gokhale Avatar answered Oct 23 '22 03:10

Saurabh Gokhale


Because the new C() is converted to a string, and then passed to println(). Basically, here's what happens:

1. Concatenate "A" with new C():
  a. Call String.valueOf(new C()):
    i. print "B"
    ii. return "C"
  b. Concatenate "A" and "C"
2. Pass "AC" to println
3. Print "AC"

AFAIK (I'm not 100% sure) string concatenation uses String#valueOf(Object) rather than directly calling Object#toString(). That's why "foo" + null is "foonull" rather than [throw a NullPointerException].

like image 2
Matt Ball Avatar answered Oct 23 '22 03:10

Matt Ball