Passing a String by Reference in Java?

I am used to doing the following in C :

void main() {
    String zText = "";
    fillString(zText);
    printf(zText);
}

void fillString(String zText) {
    zText += "foo";
}

And the output is:

foo

However, in Java, this does not seem to work. I assume because the String object is copied instead of passed by referenced. I thought Strings were objects, which are always passed by reference.

What is going on here?


You have three options:

  • Use a StringBuilder:

    StringBuilder zText = new StringBuilder ();
    void fillString(StringBuilder zText) { zText.append ("foo"); }
    
  • Create a container class and pass an instance of the container to your method:

    public class Container { public String data; }
    void fillString(Container c) { c.data += "foo"; }
    
  • Create an array:

    new String[] zText = new String[1];
    zText[0] = "";
    
    void fillString(String[] zText) { zText[0] += "foo"; }
    
  • From a performance point of view, the StringBuilder is usually the best option.


    In Java nothing is passed by reference. Everything is passed by value . Object references are passed by value. Additionally Strings are immutable . So when you append to the passed String you just get a new String. You could use a return value, or pass a StringBuffer instead.


    What is happening is that the reference is passed by value, ie, a copy of the reference is passed. Nothing in java is passed by reference, and since a string is immutable, that assignment creates a new string object that the copy of the reference now points to. The original reference still points to the empty string.

    This would be the same for any object, ie, setting it to a new value in a method. The example below just makes what is going on more obvious, but concatenating a string is really the same thing.

    void foo( object o )
    {
        o = new Object( );  // original reference still points to old value on the heap
    }
    
    链接地址: http://www.djcxy.com/p/15210.html

    上一篇: 为什么这个工作? 不合逻辑的数组访问

    下一篇: 在Java中通过引用传递字符串?