10

I want to send a string to a method and change the string there. The method should return void. Example:

String s = "Hello";
ChangeString(s);

String res = s;
//res = "HelloWorld"
-------------------------------------------

private void ChageString(String s){
s = s + "World";
}

How can I do it in Java? Can it be done without adding another class?

Thanks! PB

bahar_p
  • 441
  • 1
  • 8
  • 18
  • 1
    See http://stackoverflow.com/questions/11164675/mutable-strings-in-java – fdomig Aug 12 '12 at 18:32
  • If you really need to do it in a method returning void there is a dirty hack to do so. -> http://blogs.atlassian.com/2008/07/magic_trick_in_java But that is usually not the way to go! – zip Aug 12 '12 at 18:40
  • seems to be a duplicate of [enter link description here][1] [1]: http://stackoverflow.com/questions/9183703/passing-a-string-to-a-function – Cyber Aug 12 '12 at 18:50

7 Answers7

17

Your method cannot work with the current interface because of two reasons:

  • Strings are immutable. Once you have created a string you cannot later change that string object.
  • Java uses pass-by-value, not pass-by-reference. When you assign a new value to s in your method it only modifies the local s, not the original s in the calling code.

To make your method work you need to change the interface. The simplest change is to return a new string:

private String changeString(String s){
    return s + "World";
}

Then call it like this:

String s = "Hello";
String res = changeString(s);

See it working online: ideone

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    private String changeString(...), return type shouldn't be void. – kosa Aug 12 '12 at 18:32
  • How can I return a value from a method that returns void? – bahar_p Aug 12 '12 at 18:32
  • They are, yes. But there is some nasty hack that works in some conditions, which makes them mutable :) – dantuch Aug 12 '12 at 18:33
  • please remove all the "bad idea" suggestions and just suggest using a wrapper class with a mutable member variable. i don't think any newbies out there need to see these "suggestions"! ;) – jtahlborn Aug 12 '12 at 19:43
  • 4
    Java is not pass by value. Please remove irrelavent resons. – Jack Jul 24 '17 at 15:41
  • agree with @Jack . The reason is just immutability of String. – Ali Abazari Feb 16 '18 at 02:11
  • Java is very much pass by value. See https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value . If Java was pass by reference, a new, immutable string would be created and stored in the mem reference that was passed into the method. This would result in the string's value changing for the calling method. – zerpsed Jun 20 '19 at 14:08
3

Use StringBuffer instead of String it will solve your problem.

public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Hello");
    changeString(s);
    String res = s.toString();
    //res = "HelloWorld"
}

private static void changeString(StringBuffer s){
    s.append("World");
}

Or if you really need to use only String so here is the solution using reflection:

public static void main(String[] args) {
    String s = "Hello";
    changeString(s);
    String res = s;
    //res = "HelloWorld"
}

private static void changeString(String s){
    char[] result = (s+"World").toCharArray();
    try {
        Field field = s.getClass().getDeclaredField("value");
        field.setAccessible(true);
        field.set(s, result);

    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException |
            IllegalAccessException  e1) {
        e1.printStackTrace();
    }
}
Alex
  • 51
  • 2
1

Nope, can't be done while returning void.

Java passes parameters by value. Strings are immutable, so you can't change its value. You're out of luck.

You can do this:

private String changeString(String original) {
    return original + " World";
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

You could wrap up your string in an object:

public class StringWrapper {
    String _str;
    public StringWrapper(String str) { set(str); }
    public void set(String str) { _str = str; }
    public String toString() { return _str; }
}

Allowing you to do:

StringWrapper s = new StringWrapper("Hello");
ChangeString(s);

String res = s + "";
//res = "HelloWorld"
private void ChageString(StringWrapper s) {
    s.set(s + "World");
}
Eric
  • 95,302
  • 53
  • 242
  • 374
0

No, a Java String is immutable and cannot be changed. You can just return a new String and assign it to the same variable.

Even further: String is declared as final, so you can't extend String to add new behaviour

klaustopher
  • 6,702
  • 1
  • 22
  • 25
0

Use the StringBuffer/StringBuilder to change the string. Strings in java are immutable, this means that once they are assigned a value, they cannot be changed, the code that seems to be changing the string actually makes a new object. Here's something on string buffer, hope it helps. :)

praxmon
  • 5,009
  • 22
  • 74
  • 121
0

is it acceptable?

//solution1:
private static void ChangeString(String[] s){
    s[0] = s[0] + "World";
}
public static void main(String[] args)
{
    String[] s = new String[]{"Hello"};
    ChangeString(s);

    String res = s[0];
    System.out.println(res);
}

//solution2:
class Container {
    public Container(String value) {
        this.value = value;
    }

    public String value;
}

public class Main{
    private static void ChangeString(Container s) {
        s.value = s.value + "World";
    }

    public static void main(String[] args) {
        Container s = new Container("hello");
        ChangeString(s);

        String res = s.value;
        System.out.println(res);
    }
}
Amir
  • 1,638
  • 19
  • 26