Page 1 of 1

Why is toString() not implicitly called?

Posted: Wed Jan 27, 2016 12:13 pm
by krohani
In the following code:

Code: Select all

StringBuilder sb = new StringBuilder("8");
int i = 8;
System.out.println(8 + i + sb);
The correct answer given is that it does not compile. However, I have seen many instances where an object is passed into the println and there is an implicit call to it's toString(). What am I not understanding here?

Thanks!

Re: Why is toString() not implicitly called?

Posted: Wed Jan 27, 2016 1:52 pm
by admin
When you pass an object to println, the println will internally call toString on it. However, here, the expression 8+i+sb has to be evaluated first before the result can be passed to println. The compilation error is because this expression cannot be evaluated as explained in the explanation.

Re: Why is toString() not implicitly called?

Posted: Wed Jan 27, 2016 4:11 pm
by krohani
Got it, thank you!