Please tell me a real time situation to compare String
, StringBuffer
, and StringBuilder
?
String
The String class represents character strings. All string literals in Java program, such as "abc"
are implemented as instances of this class.
String objects are immutable once they are created we can't change. (Strings are constants)
If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern()
method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference.
+
), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String heapSCP = new String("Yash");
heapSCP.concat(".");
heapSCP = heapSCP + "M";
heapSCP = heapSCP + 777;
// For Example: String Source Code
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
String literals are stored in StringConstantPool
.
String onlyPool = "Yash";
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's. StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
StringBuffer threadSafe = new StringBuffer("Yash");
threadSafe.append(".M");
threadSafe.toString();
StringBuilder nonSync = new StringBuilder("Yash");
nonSync.append(".M");
nonSync.toString();
StringBuffer and StringBuilder are having a Special methods like.,
replace(int start, int end, String str)
and reverse()
.
NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of
Appendable Interface
.
When to use which one.
If a you are not going to change the value every time then its better to Use String Class
. As part of Generics if you want to Sort ComparableString Class
.
//ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
Set set = new TreeSet();
set.add( threadSafe );
System.out.println("Set : "+ set);
If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.