Passing a String by Reference in Java?

JavaStringPass by-Reference

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

What is happening is that the reference is passed by value, i.e., 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, i.e., 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
}

Solution 4 - Java

java.lang.String is immutable.

I hate pasting URLs but [https://docs.oracle.com/javase/10/docs/api/java/lang/String.html](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html "String Documentation") is essential for you to read and understand if you're in java-land.

Solution 5 - Java

All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.

The assignment

zText += foo;

is equivalent to:

zText = new String(zText + "foo");

That is, it (locally) reassigns the parameter zText as a new reference, which points to a new memory location, in which is a new String that contains the original contents of zText with "foo" appended.

The original object is not modified, and the main() method's local variable zText still points to the original (empty) string.

class StringFiller {
  static void fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value:

If you want to modify the string, you can as noted use StringBuilder or else some container (an array or an AtomicReference or a custom container class) that gives you an additional level of pointer indirection. Alternatively, just return the new value and assign it:

class StringFiller2 {
  static String fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
    return zText;
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    zText = fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value: foo

This is probably the most Java-like solution in the general case -- see the Effective Java item "Favor immutability."

As noted, though, StringBuilder will often give you better performance -- if you have a lot of appending to do, particularly inside a loop, use StringBuilder.

But try to pass around immutable Strings rather than mutable StringBuilders if you can -- your code will be easier to read and more maintainable. Consider making your parameters final, and configuring your IDE to warn you when you reassign a method parameter to a new value.

Solution 6 - Java

objects are passed by reference, primitives are passed by value.

String is not a primitive, it is an object, and it is a special case of object.

This is for memory-saving purpose. In JVM, there is a string pool. For every string created, JVM will try to see if the same string exist in the string pool, and point to it if there were already one.

public class TestString
{
	private static String a = "hello world";
	private static String b = "hello world";
	private static String c = "hello " + "world";
	private static String d = new String("hello world");

	private static Object o1 = new Object();
	private static Object o2 = new Object();

	public static void main(String[] args)
	{
		System.out.println("a==b:"+(a == b));
		System.out.println("a==c:"+(a == c));
		System.out.println("a==d:"+(a == d));
		System.out.println("a.equals(d):"+(a.equals(d)));
		System.out.println("o1==o2:"+(o1 == o2));
		
		passString(a);
		passString(d);
	}
	
	public static void passString(String s)
	{
		System.out.println("passString:"+(a == s));
	}
}

/* OUTPUT */

a==b:true
a==c:true
a==d:false
a.equals(d):true
o1==o2:false
passString:true
passString:false

the == is checking for memory address (reference), and the .equals is checking for contents (value)

Solution 7 - Java

String is an immutable object in Java. You can use the StringBuilder class to do the job you're trying to accomplish, as follows:

public static void main(String[] args)
{
    StringBuilder sb = new StringBuilder("hello, world!");
    System.out.println(sb);
    foo(sb);
    System.out.println(sb);
    
}

public static void foo(StringBuilder str)
{
    str.delete(0, str.length());
    str.append("String has been modified");
}

Another option is to create a class with a String as a scope variable (highly discouraged) as follows:

class MyString
{
    public String value;
}

public static void main(String[] args)
{
    MyString ms = new MyString();
    ms.value = "Hello, World!";
    
}

public static void foo(MyString str)
{
    str.value = "String has been modified";
}

Solution 8 - Java

String is a special class in Java. It is Thread Safe which means "Once a String instance is created, the content of the String instance will never changed ".

Here is what is going on for

 zText += "foo";

First, Java compiler will get the value of zText String instance, then create a new String instance whose value is zText appending "foo". So you know why the instance that zText point to does not changed. It is totally a new instance. In fact, even String "foo" is a new String instance. So, for this statement, Java will create two String instance, one is "foo", another is the value of zText append "foo". The rule is simple: The value of String instance will never be changed.

For method fillString, you can use a StringBuffer as parameter, or you can change it like this:

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

Solution 9 - Java

The answer is simple. In java strings are immutable. Hence its like using 'final' modifier (or 'const' in C/C++). So, once assigned, you cannot change it like the way you did.

You can change which value to which a string points, but you can NOT change the actual value to which this string is currently pointing.

Ie. String s1 = "hey". You can make s1 = "woah", and that's totally ok, but you can't actually change the underlying value of the string (in this case: "hey") to be something else once its assigned using plusEquals, etc. (ie. s1 += " whatup != "hey whatup").

To do that, use the StringBuilder or StringBuffer classes or other mutable containers, then just call .toString() to convert the object back to a string.

note: Strings are often used as hash keys hence that's part of the reason why they are immutable.

Solution 10 - Java

Strings are immutable in Java.

Solution 11 - Java

This works use StringBuffer

public class test {
 public static void main(String[] args) {
 StringBuffer zText = new StringBuffer("");
    fillString(zText);
    System.out.println(zText.toString());
 }
  static void fillString(StringBuffer zText) {
    zText .append("foo");
}
}

Even better use StringBuilder

public class test {
 public static void main(String[] args) {
 StringBuilder zText = new StringBuilder("");
    fillString(zText);
    System.out.println(zText.toString());
 }
  static void fillString(StringBuilder zText) {
    zText .append("foo");
}
}

Solution 12 - Java

String is immutable in java. you cannot modify/change, an existing string literal/object.

String s="Hello"; s=s+"hi";

Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".

However, for bringing mutability we have StringBuilder and StringBuffer.

StringBuilder s=new StringBuilder(); s.append("Hi");

this appends the new value "Hi" to the same refernce s. //

Solution 13 - Java

Aaron Digulla has the best answer so far. A variation of his second option is to use the wrapper or container class MutableObject of the commons lang library version 3+:

void fillString(MutableObject<String> c) { c.setValue(c.getValue() + "foo"); }

you save the declaration of the container class. The drawback is a dependency to the commons lang lib. But the lib has quite a lot of useful function and almost any larger project i have worked on used it.

Solution 14 - Java

For passing an object (including String) by reference in java, you might pass it as member of a surrounding adapter. A solution with a generic is here:

import java.io.Serializable;

public class ByRef<T extends Object> implements Serializable
{
	private static final long serialVersionUID = 6310102145974374589L;

	T v;

	public ByRef(T v)
	{
		this.v = v;
	}

	public ByRef()
	{
		v = null;
	}

	public void set(T nv)
	{
		v = nv;
	}

	public T get()
	{
		return v;
	}

// ------------------------------------------------------------------

	static void fillString(ByRef<String> zText)
	{
		zText.set(zText.get() + "foo");
	}

	public static void main(String args[])
	{
		final ByRef<String> zText = new ByRef<String>(new String(""));
		fillString(zText);
		System.out.println(zText.get());
	}
}

Solution 15 - Java

For someone who are more curious

class Testt {
    static void Display(String s , String varname){
        System.out.println(varname + " variable data = "+ s + " :: address hashmap =  " + s.hashCode());
    }

    static void changeto(String s , String t){
        System.out.println("entered function");
        Display(s , "s");
        s = t ;
        Display(s,"s");
        System.out.println("exiting function");
    }

    public static void main(String args[]){
        String s =  "hi" ;
        Display(s,"s");
        changeto(s,"bye");
        Display(s,"s");
    }
}

> Now by running this above code you can see how address hashcodes change with String variable s . > a new object is allocated to variable s in function changeto when s is changed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoren JohnsonView Question on Stackoverflow
Solution 1 - JavaAaron DigullaView Answer on Stackoverflow
Solution 2 - JavazedooView Answer on Stackoverflow
Solution 3 - JavaEd S.View Answer on Stackoverflow
Solution 4 - JavaRyan FernandesView Answer on Stackoverflow
Solution 5 - JavaDavid MolesView Answer on Stackoverflow
Solution 6 - JavajanetsmithView Answer on Stackoverflow
Solution 7 - JavaFadi Hanna AL-KassView Answer on Stackoverflow
Solution 8 - JavaDeepNightTwoView Answer on Stackoverflow
Solution 9 - Javaak_2050View Answer on Stackoverflow
Solution 10 - JavaGrzegorz OledzkiView Answer on Stackoverflow
Solution 11 - JavaMohammed RafeeqView Answer on Stackoverflow
Solution 12 - JavagauravJView Answer on Stackoverflow
Solution 13 - Javauser2606740View Answer on Stackoverflow
Solution 14 - JavaSam GinrichView Answer on Stackoverflow
Solution 15 - JavaRajesh kumarView Answer on Stackoverflow