Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass-by-value (StringBuilder vs String) [duplicate]

I do not understand why System.out.println(name) outputs Sam without being affected by the method's concat function, while System.out.println(names) outputs Sam4 as a result of the method's append method. Why is StringBuilder affected and not String? Normally, calling methods on a reference to an object affects the caller, so I do not understand why the String result remains unchanged. Thanks in advance

public static String speak(String name) {
    name = name.concat("4");
    return name;
}

public static StringBuilder test(StringBuilder names) {
    names = names.append("4");
    return names; 
}

public static void main(String[] args) {
    String name = "Sam";
    speak(name);
    System.out.println(name); //Sam
    StringBuilder names = new StringBuilder("Sam");
    test(names);
    System.out.println(names); //Sam4
}
like image 789
Helenesh Avatar asked Jul 13 '15 12:07

Helenesh


People also ask

Is StringBuilder more efficient than String?

So from this benchmark test we can see that StringBuilder is the fastest in string manipulation. Next is StringBuffer , which is between two and three times slower than StringBuilder .

Is StringBuilder pass by reference?

Because it is passed by reference. The reference to the StringBuilder is passed by value. You can add characters and they will be in the instance after the method returns. Same way you can pass a Collection and add values inside the invoke method - these will be preserved.

Which is better StringBuilder or String?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

Should you use StringBuilder to construct large texts instead of just adding strings?

I think we should go with StringBuilder append approach. Reason being : The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.


1 Answers

Because when you call speak(name);, inside speak when you do

name = name.concat("4");

it creates a new object because Strings are immutable. When you change the original string it creates a new object,I agree that you are returning it but you are not catching it.

So essentially what you are doing is :

name(new) = name(original) + '4'; // but you should notice that both the names are different objects.

try

String name = "Sam";
name = speak(name);

Of course now I think there is no need to explain why it's working with StringBuilder unless if you don't know that StringBuilder is mutable.

like image 127
Karthik Avatar answered Sep 27 '22 19:09

Karthik