• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

String VS StringBuffer

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
We don't have time for this. We've gotta save the moon! Or check this out:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic