• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

appending StringBuffer to String

 
anuj bhatnagar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
Jart Bo
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
anuj bhatnagar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you're right!
 
anuj bhatnagar
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic