2017  Kodetalk | Feedback | Privacy Policy | Terms | About

What is the difference between String and final StringBuilder/StringBuffer

I got this question as a interview question. The interviewer asked me like i have a variable

String str = "test";


final StringBuffer/StringBuilder str = new StringBuider/StringBuffer("test");

Now what is the difference between these two and asked what is the difference between final and Immutable in Java. What could be the right ans for this questions?


Ok, things you should know like any final variable means you can't change the object's reference to point to another reference. Where Immutable means that actual object's value can't be changed, but you can change its reference to another one.

Means when you creating any variable of type String, as the String is a final class, if you trying to change the value, JVM will create a new object with new value and give the reference to the variable. But in case of

final StringBuffer/StringBulder str;

Here, once you assigned a object to the variable str, you cannot assign any other object to the same variable.

Answer is