String vs StringBuilder Explained
Lets see this through a very interesting example :-
Suppose we have a string and a StringBuilder as given below :-
When i append the string with the “new” string , the string reference “s” ,
still points to the original string , while the StringBuilder reference sb is showing the modification done in the magic method why is such case ??
1.Because Strings are Immutable .
what does that mean?
Once a String Object is being in heap , we can’t change the state of the string object , there will be only one state of a String Object .
Its state can’t mutate.
On the Other Hand , For StringBuilder :-
It can mutate its object state as many times as it wants , it will be happening on the Same Object .
String s = "I am a String ";
StringBuilder sb = new StringBuilder("I am a StringBuilder ");
System.out.println(s);
System.out.println(sb);
magic(s,sb);
System.out.println(s);
System.out.println(sb);
public static void magic(String s, StringBuilder sb){
s = s + "new" ;
sb = sb.append("new");
}
I am a String
I am a StringBuilder
I am a String
I am a StringBuilder new
In this cases , when we wrote s = s + “new” , Here String will create a new String Object and s will be pointing to that object in the method .
2. Strings Override the equals Method.
class Main
{
private static final String STR = "COMMON";
public static void main(String[] args)
{
String s1 = new String(STR);
String s2 = new String(STR);
System.out.println(s1.equals(s2));
StringBuilder sb1 = new StringBuilder(STR);
StringBuilder sb2 = new StringBuilder(STR);
System.out.println(sb1.equals(sb2));
}
}
Output 1st -> true
Output 2nd -> false
Here , StringBuilder doesn’t have the implementation of equals method , so it uses the Objects Equals Method , which basically compares the memory reference , which is not same as two different StringBuilder objects are created .
3.Strings implements the comparable
The String
class implements the Comparable
interface, while StringBuilder
doesn’t. To illustrate, consider the following code, which throws ClassCastException
since StringBuilder
doesn’t provide any mechanism for string comparison.
import java.util.Set;
import java.util.TreeSet;
class Main
{
public static void main(String[] args)
{
Set<String> colors = new TreeSet<>();
colors.add(new String("Red"));
colors.add(new String("Blue"));
colors.add(new String("green"));
Set<StringBuilder> codes = new TreeSet<>();
try {
codes.add(new StringBuilder("#008200"));
codes.add(new StringBuilder("#ff0000"));
codes.add(new StringBuilder("#006400"));
}
catch (ClassCastException ex) {
System.out.println(ex.getMessage());
}
}
}
OUTPUT :- java.lang.StringBuilder cannot be cast to java.lang.Comparable
5. Performance
StringBuilder
is speedy and consumes less memory than a string while performing concatenations. This is because string is immutable in Java, and concatenation of two string objects involves creating a new object.
To illustrate, consider the following code, which logs the time taken by both string and StringBuilder
objects on multiple concatenations.
class Main
{
private static final String STR = "TEST";
public static String stringConcatenation()
{
String s = STR;
for (int i = 0; i < Short.MAX_VALUE; i++) {
s = s + STR;
}
return s;
}
public static String stringBuilderConcatenation()
{
StringBuilder sb = new StringBuilder(STR);
for (int i = 0; i < Short.MAX_VALUE; i++) {
sb.append(STR);
}
return sb.toString();
}
public static void main(String[] args)
{
long start = System.nanoTime();
stringConcatenation();
long end = System.nanoTime();
System.out.println("The time taken by string concatenation: "
+ (end - start) + "ns");
start = System.nanoTime();
stringBuilderConcatenation();
end = System.nanoTime();
System.out.println("The time taken by StringBuilder concatenation: "
+ (end - start) + "ns");
}
}
The time taken by string concatenation: 504774386ns
The time taken by StringBuilder concatenation: 1081315ns
CONCLUSION
— — — — — — — — — —
A String can be used when immutability is required, or concatenation operation is not required. A StringBuilder
can be used when a mutable string is needed without the performance overhead of constructing lots of strings along the way.
Final Keyword Explained Here :-
https://medium.com/@java-Spring-Decoded/final-keyword-in-java-c197c6a28345
MultiThreaded Singelton Explained Here :-
https://medium.com/@java-Spring-Decoded/multithreaded-singleton-java-class-f3b7d633752b
Immutable Classes Explained Here :-
Equals Method Explained Here :-
https://medium.com/@java-Spring-Decoded/equals-method-in-java-34ff82f1180