Two Laptop Bag*
The moose likes Beginning Java and the fly likes String VS StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String VS StringBuffer" Watch "String VS StringBuffer" New topic
Author

String VS StringBuffer

Suresh Rajadurai
Ranch Hand

Joined: Feb 22, 2007
Posts: 58
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
Marshal

Joined: Mar 22, 2005
Posts: 41180
    
  45
"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.

Ping & DNS - my free Android networking tools app
 
Don't get me started about those stupid light bulbs.
 
subject: String VS StringBuffer
 
Similar Threads
Remove Chars from a String?
2 complex problems
Doubt in Strings
2 complex problems
StringBuffer