Passing a String by Reference in Java?

Soren Johnson picture Soren Johnson · Aug 13, 2009 · Viewed 189.9k times · Source

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?

Answer

Aaron Digulla picture Aaron Digulla · Aug 13, 2009

You have three options:

  1. Use a StringBuilder:

    StringBuilder zText = new StringBuilder ();
    void fillString(StringBuilder zText) { zText.append ("foo"); }
    
  2. 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"; }
    
  3. 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.