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.
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.
If you like our products and services, please help us by posting your review here.
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?
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.
If you like our products and services, please help us by posting your review here.