Can I change String object's value passed to my method?

merveotesi picture merveotesi · Nov 21, 2011 · Viewed 33.8k times · Source

I found the following question Is Java "pass-by-reference" or "pass-by-value"?.

I read almost all of it, but could not find out yet what should I do if I want the foo(-) method, to change my String's value? (maybe or not reference too, it doesn't matter to me).

void foo(String errorText){ 
    errorText="bla bla";
}

int main(){ 
    String error="initial"; 
    foo(error); 
    System.out.println(error);
}

I want to see bla bla on the console. Is it possible?

Answer

Jack Edmonds picture Jack Edmonds · Nov 21, 2011

You can't change the value of errorText in foo as the method is currently declared. Even though you are passing a reference of the String errorText into foo, Java Strings are immutable--you can't change them.

However, you could use a StringBuffer (or StringBuilder). These classes can be edited in your foo method.

public class Test {
    public static void foo(StringBuilder errorText){ 
        errorText.delete(0, errorText.length());
        errorText.append("bla bla");
    }

    public static void main(String[] args) { 
        StringBuilder error=new StringBuilder("initial");
        foo(error); 
        System.out.println(error);
    }
}

Other solutions are to use a wrapper class (create a class to hold your String reference, and change the reference in foo), or just return the string.