Java - Why is the following code printing “BAC” and not “ABC”?

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 
+7
source share
3 answers

Here you need to understand two concepts: the evaluation rule from left to right Java and .

 "A"+new C() 

following the same rule. First it gets an “A,” which is a string literal, puts it somewhere. Then he evaluates

 new C() 

first, construct a C Object , then call the toString() method of C and get the value of C, which is " C ", then combines " A " and " C " together with println " AC ".

Inside the toString() method of the C object, there is System.out.print("B"); which is called when Java evaluates the above expression. It is printed before the evaluation is completed.
This is why " B " is printed first

+6
source

The score looks something like this:

 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"

+9
source

Since new C() converted to a string and then passed to println() . Basically, this is 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() . Therefore, "foo" + null "foonull" , and not [throw a NullPointerException] .

+2
source

All Articles