aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes appending StringBuffer to String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "appending StringBuffer to String " Watch "appending StringBuffer to String " New topic
Author

appending StringBuffer to String

anuj bhatnagar
Ranch Hand

Joined: Aug 06, 2007
Posts: 31


executing the following code clearly says that Appendin StringBuffer and String instances using '+' operator creates the new object to be a type of String while using append method of StringBuffer class keeps it as StringBuffer which is easily understood.
My doubt is how can it make the new object of type String while using '+' operator? It seems that before appending, '+' converts StringBuffer into String and then append it with String object. Can any one give me some more clarification on this.


thanks & regards,<br />Anuj Bhatnagar
Jart Bo
Ranch Hand

Joined: Oct 22, 2007
Posts: 144
Hi anuj,

I believe the + operator is only applicable to Strings. The System.out.println() has an implicit call to the toString() method of whatever is being printed.


SCJP, SCWCD
anuj bhatnagar
Ranch Hand

Joined: Aug 06, 2007
Posts: 31
No it has nothing to do with System.out.println(), its true that it calls toString() method of its argument but even without that adding one StringBuffer to String and assigning it back to StringBuffer says incompatible type while assigning the new object to String is allowed.
Jart Bo
Ranch Hand

Joined: Oct 22, 2007
Posts: 144
Hey anuj,

Gotcha! Running your code outputs:

class java.lang.StringBuffer
class java.lang.String

It looks like String object + StringBuffer object results to a new String, which is legal.

String object + StringBuffer object does not result to a StringBuffer.
sridhar row
Ranch Hand

Joined: Jan 16, 2008
Posts: 162
I guess it has to do with the String concatenation operator +. If either of the operands is a String it results in a String.
Jart Bo
Ranch Hand

Joined: Oct 22, 2007
Posts: 144
I guess you're right!
anuj bhatnagar
Ranch Hand

Joined: Aug 06, 2007
Posts: 31
thanks guys, I knew that it results in String.
It is correct that it has to do with '+' operator.
If you add String instance to any other object of any class , then toString() method is called before appending/concatenating that object to String and results is String.

Thanks for your the views.
 
Don't get me started about those stupid light bulbs.
 
subject: appending StringBuffer to String