About Question enthuware.ocpjp.v7.2.1718 :

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

Moderator: admin

Post Reply
ThufirHawat
Posts: 28
Joined: Wed Feb 25, 2015 9:03 am
Contact:

About Question enthuware.ocpjp.v7.2.1718 :

Post 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

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

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

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

Mark7777
Posts: 32
Joined: Tue Apr 12, 2016 9:19 pm
Contact:

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

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

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

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

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

Post Reply

Who is online

Users browsing this forum: No registered users and 68 guests