File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String VS StringBuffer" Watch "String VS StringBuffer" New topic

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,


Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42959
"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.
I agree. Here's the link:
subject: String VS StringBuffer
It's not a secret anymore!