StringBuffer sb=new StringBuffer("Hello");
sb.append("welcome");//working
sb.concat("hi");//not working
Why can't i use concat here??
StringBuffer sb=new StringBuffer("Hello");
sb.append("welcome");//working
sb.concat("hi");//not working
Why can't i use concat here??
Because there's no concat
method for StringBuffer
or StringBuilder
:
http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
Because there is no method named concat in StringBuffer.The equivalent one is append.
You might be thinking in term's of the method concat in String.Both are different.In String the concat method return's a new String each time since String is immutable but in case of StringBuffer the same object is modified.Hence when you have to append large amount of data always go for StringBuffer or StringBulider(if your not using threads) which will give you more performance.
String Code:
String str="hello";
String strCon=str.concat("world");//return's new concatenated string,str not changed
StringBuffer/Builer Code:
StringBuffer strBuff=new StringBuffer("hello");
strBuff.append("world");//strBuff changed
StringBuffer or StringBuilder are not String, java.lang.String has method concat(String). StringBuffer is thread safe, StringBuilder is not.
Why do those 3 classes exist?
Firstly, the String class is immutable: if You call a method on a String object, that changes something in it, You'll get a new String in a result.
But, in some cases that's not what You might want, maybe because You process strings a lots and don't want to create new object every time You change something. That's the reason why StringBuffer was added.
StringBuffer was designed also to be thread-safe. That means You get a little extra overhead for most of the methods. So if Your program requires a lot of String crunching (jgrep alike) it might become a bottleneck.
Finally, StringBuilder was added. That's basically StringBuffer without synchronization.
And what about that strange naming? Ironically, to avoid confusion... Since concat is already in String, but returns a new object, the best to do was to add another method.