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

3

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

7 Comments

private String changeString(...), return type shouldn't be void.
How can I return a value from a method that returns void?
They are, yes. But there is some nasty hack that works in some conditions, which makes them mutable :)
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"! ;)
Java is not pass by value. Please remove irrelavent resons.
|
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();
    }
}

Comments

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";
}

Comments

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");
}

Comments

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

Comments

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. :)

Comments

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.