java

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 78 answers

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

    name = name.concat("4");
    

    it creates a new object because String s 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.


    Looking at the Javadoc for String , you will find that

    [...] String objects are immutable [...].

    This means concat(String) does not change the String itself, but constructs a new String .

    StringBuilder s, on the other hand, are mutable. By calling append(CharSequence) , the object itself is mutated.


    Okay, what is speak method doing?

    First of all,

    name.concat("4");
    

    creates new object, which is equal to name , concatenated with "4" .

    So, the line

    name = name.concat(4);
    

    redefines local (for speak method) variable name .

    Then you return the reference to this new value with

    return name;
    

    So, the original variable, passed within method is not modified, but the method returns modified value.

    In the test method you actually modify variable without modifying the reference (the StringBuilder class is mutable, so variable if this type can be modified).

    Then we can see another question arising: why StringBuilder.append returns value, where it can seem redundant. The answer to this question lies in the description of "builder" pattern, for which it is the usual way of implementing modification methods. See wikipedia on Builder pattern.

    链接地址: http://www.djcxy.com/p/3512.html

    上一篇: 更改方法Java中的变量值

    下一篇: java的