wood burning stoves 2.0*
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


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: 42035
    
  64
"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
 
GeeCON Prague 2014
 
subject: String VS StringBuffer