String vs StringBuffer返回值

Roh*_*aha 4 java string stringbuffer

能否请您解释为什么在下面的代码String和StringBuffer区别对待,当价值被附加StringBuffer,但不是在字符串。

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

串罗汉

字符串缓冲区Rohan Kushwaha

Rai*_*ner 5

在主要方法

String str = new String("String Rohan ");
Run Code Online (Sandbox Code Playgroud)

str是指向Java-JVM的堆内存中某个位置的引用(指针)。让我们称这个地方为A

str-> A

private static void  strUpdate(String str){
    //str here is still pointing to A, but technically this parameter
    //is a copy of the reference of the str pointer in the main-method
    //pointing to the same place in the heap
    //str->A
    str += "Kushwaha";
    // this line is short for str = str + "Kushwaha"
    //what happens here that you create a new String-Object in the heap (B)
    //and assigne the new value "String Rohan Kushwaha" to the new pointer
    //if you print it out now (within this method) you get what you would 
    //expect
    System.out.println(str);
    //will result in "String Rohan Kushwaha"
}
Run Code Online (Sandbox Code Playgroud)

但是主方法的str-pointer仍指向堆中仍然只有“ String Rohan”的位置A。因此,一旦离开方法strUpdate(...)的范围,复制的指针(已重新分配到位置B)就会被删除。

希望这能有所帮助...

我想这对您的理解很有帮助

Java是“按引用传递”还是“按值传递”?