Difference Between String and StringBuffer in Java

A Hot topic for the Interview Room

Akshata Pawar
3 min readJan 23, 2021

🔸What is the difference between String and StringBuffer?
🔸What is mutability and immutability?

String

Lets first illustrate the below lines of code in your code editor:
Example:

Can you guess the output of this above code❓

The output will be [Happy] and not [HappyLearning]

🤔Why so?

Because in the 4th line of the above code we are creating a new String object s, which is pointing to “Happy”.

Now as the Strings are immutable we are not allowed to perform any changes on that String object.

If we are trying to change that String object, then the separate copy of the object will be created with the new changes which in this case is [HappyLearning]. But still, the ‘s’ object is containing the value [Happy] and not [HappyLearning].
In the 5th line of code when we are concatenating a string object,|s.concat(“Learning”)| we are not assigning the string object to any reference variable , then automatically that object will be available for the garbage collector.

StringBuffer

Lets now illustrate the below lines of code in your code editor:
Example:

Can you guess the output of this above code❓

The output will be [HappyLearning]

🤔Why so?

Because of the mutability behavior of StringBuffer.
Mutable means we can change, when we create an object using StringBuffer, that object we can easily change, and that’s why StringBuffer is mutable.
That is why the output of the above code will be [HappyLearning]

StringBuffer is synchronized(Thread-safe)-which means two threads cannot be execute the method at the same time.

If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on LinkedIn or Twitter. Thank you🤍

--

--