Page 1 of 1

About Question enthuware.ocpjp.v7.2.1718 :

Posted: Mon Oct 05, 2015 11:58 pm
by ThufirHawat
as its says:
Note that + operator is overloaded only for String and not for StringBuilder.
How +(plus) operator can be overloaded? "+ operator is overloaded"? I can't figure out what this can be interpreted as the plus operator can't be overloaded in java. It only have one function.

background:
http://stackoverflow.com/questions/1686 ... ng-in-java
http://javarevisited.blogspot.com.br/20 ... rator.html

Re: About Question enthuware.ocpjp.v7.2.1718 :

Posted: Tue Oct 06, 2015 1:11 am
by admin
You (i.e. a Java programmer) can't overload + operator. But Java language itself has already overloaded it. That is why you are able to apply + operator to String operands.

Re: About Question enthuware.ocpjp.v7.2.1718 :

Posted: Sat Oct 13, 2018 9:29 pm
by Mark7777
All right, so I thought println() would automatically call toString() on the StringBuilder and return 8 which would be concatenated to the added numbers. I thought so because System.out.println(sb); does exactly that and returns 8. So why doesn't println(8 + i + sb); do the same and call toString() on sb here? Is it because the overloaded + concatenater is invoked and a different set of rules apply?

Re: About Question enthuware.ocpjp.v7.2.1718 :

Posted: Sat Oct 13, 2018 10:58 pm
by admin
If you pass an object reference to println, the code inside println calls toString() on that reference* to get a String, which it then prints.
In case of println(8 + i + sb); , the expression 8 + i + sb needs to be evaluated first. The result of evaluation of this expression will need to be passed to the println method. But how will you evaluate 8 + i + sb, if the + operator can't be applied to int and StringBuilder arguments?

* conditions apply - The code inside println checks if the reference is null, if it is null, the code just prints "null" instead of invoking toString on it.