Interview Question  When to used String, String Buffer ,String Builder
 String, String Buffer, String Builder.
Many interviews asked this question many times that what is the use of String, String Buffer or String
Builder. Here I try to explain what is used of String, String Buffer or String Builder. First, we need to know the simple Definition of String, String Buffer and String Builder.

What is a String?

A Java String is a sequence of characters in java which is present in java.lang package.
Once created, a string is immutable its value cannot be changed.
Strings are always the same, once designed its value can not be modified.

Two ways to create a String:

By string literal: Using double-quotes.
For Example String str=“Hello”;

By new keyword: Using a keyword “new”.
For Example String str=new String(“Hello”);

What is a String Buffer?

StringBuffer class is used to create a mutable object. It represents a growable and writable character sequence. StringBuffer is thread-safe. StringBuffer is synchronized.
String Buffer comes in JDK1.0.

What is a String Builder?

String Builder class is used to create a mutable object. It represents a growable and writable character sequence. String Builder is a non-thread-safe. String Builder is non-synchronized.
String Builder comes in JDK1.5.

When to use String?

If you have a String and you don't want to perform any insert, update, delete operation on that String by applying substring() or concat() method or else If you don't want to perform any manipulation on a String.
A string value is not going to be changed its remains constant then always goes with a String

For Example:
You can apply String on names for example if a class has 10,000 students' names which contain mostly the same name then you can use a String class. It will benefit and it will use as a memory Optimisation.

When to use String Buffer?

If you want to perform insert, update, delete(Manipulation) on a String and it will be we performed by multiple threads(multiple Java method) then you always go with String BufferString Buffer use append and insert method to perform operations on strings. It takes more time for performing an operation on String because String Buffer is a thread-safe.

When to use String Builder?

StringBuilder is introduced in JDK1.5  by looking at StringBuffer thread-safety which takes more time to perform operations on String
If you want to perform operations on a String using a single thread then you can use StringBuilder which takes less time to perform an operation on String
StringBuilder class is faster than StringBuffer
StringBuilder is not thread-safe. 

Post a Comment

Previous Post Next Post