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  
                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"
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
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].
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