In: Computer Science
When should you use the String Class as opposed to the StringBuilder Class? Describe why this answer is logical.
Solution
===================
String :- String are immutable objects,Immutable objects are not allowing modifications over their content, if we are trying to perform modifications over immutable object content then operations are allowed , but, the resultant data will not be stored back in original object, where the resultant data will be stored by creating new object.
Where as StringBuilder are mutable i.e modification is allowed over the object.
Performance wise StringBuilder is very fast and consumes less memory than String object while performing modification or concatenation operation.
for Exaple:-
String str = "ABC";
str = str+"BAC";
here two object "ABC" and "ABCBAC" is created
StringBuilder sb=new StringBuilder("ABC");
sb.append("BAC");
Here only one object is created "ABCBAC"
Conclusion:-
A String can be used when we don't change String object once created or concatenation operation is not required. A StringBuilder can be used when we have to change Object frequently and high perfromance is is needed.
For Example In application We can use String object for non changing field like user id, where as we can use StringBuilder in those field which changes like destination of employee