Change string in Java

Viewed 84338

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

7 Answers

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