Can you please explain why in the following code String
and StringBuffer
are treated differently and when value is appended in StringBuffer
but not in String.
public class MyClass {
public static void main(String args[]) {
String str = new String("String Rohan ");
StringBuffer strBfr = new StringBuffer("String Buffer Rohan ");
strUpdate(str);
strBfrUpdate(strBfr);
System.out.println(str);
System.out.println(strBfr);
}
private static void strBfrUpdate(StringBuffer strBfr){
strBfr.append("Kushwaha");
}
private static void strUpdate(String str){
str += "Kushwaha";
}
}
Output is as follows:
String Rohan
String Buffer Rohan Kushwaha
In strUpdate method you keep a reference to a String called str:
private static void strUpdate(String str){
str += "Kushwaha";
}
When you write str += "..."; It means:
str = new String(str + "...");
At this point str references the new String, but only in strUpdate method. It's not "taken back" to main.