This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String VS StringBuffer

 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

I have a confusion over the declaration of String & StringBuffer literals.

Statement 1: String s = "its a new string";
Statement 2: StringBuffer s = "Its a new string buffer";

Why , the 2nd statement gives compilation error?. But if I replace the statement with:

StringBuffer s = new StringBuffer("its a new string buffer");

it does not give compilation error.


Could anybody please throw some light on it.


much appreciated,

thanks

Suresh
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"its a new string" is a String, not a StringBuffer. As such, it can't be assigned to a StringBuffer. String literals only work as Strings, not for any other classes.

" new StringBuffer("its a new string buffer") " converts a String to a StringBuffer, so it can be assigned to one.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic