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
You need understand 2 concepts here: Java left-to-right evaluation rule and side effect.
following the same rule. It gets “A” first, which is a String literal, put it somewhere. Then it evaluate
it construct a
C Objectfirst, then invoketoString()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 aSystem.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