Why is toString() not implicitly called?

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
krohani
Posts: 31
Joined: Tue Oct 06, 2015 1:57 pm
Contact:

Why is toString() not implicitly called?

Post 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!

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why is toString() not implicitly called?

Post 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.

krohani
Posts: 31
Joined: Tue Oct 06, 2015 1:57 pm
Contact:

Re: Why is toString() not implicitly called?

Post by krohani »

Got it, thank you!

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 8 guests