String Operations, StringBuilder and StringBuffer

String Operations, StringBuilder and StringBuffer:
String is a non-primitive type in java. Strings are considered as Immutable. Before proceeding to example, Let us understand about String, StringBuilder and StringBuffer.

String is Immutable.

What is meant by Immutable?
In Java, Strings are treated as Objects. Immutable means once the object has been created it cannot be changed.

What are the advantages of String being Immutable?

  • It helps in Multi-threading, We can be sure that no one will change the string
  • Reduction in Memory usage

Two ways of Creating Strings:

  • String s1 = “StringValue”;
  • String S2 = new String(“StringValue2”);

Difference Between StringBuilder and StringBuffer:

StringBuilder StringBuffer
StringBuilder is mutable StringBuffer is mutable
StringBuilder is unsynchronized StringBuffer is Synchronized
StringBuilder is faster StringBuffer is slower when compared to StringBuilder

NOTE: StringBuffer and StringBuilder does not Override equals() and hashcode()

When to use String, StringBuffer and StringBuilder?
If our string is not going change, We use String.
If our string can change and accessed only from single thread, We can use StringBuilder.
If our string can change and can be accessed from multiple threads, We can use StringBuffer.




One thought on “String Operations, StringBuilder and StringBuffer

Leave a Reply

Your email address will not be published. Required fields are marked *