Alex Rivera | Logout

Change string in Java

Asked 2012-08-12T18:29:13.260
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

Edit
Report

3 Answers

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";
}
answered 2012-08-12T18:32:24.207
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");
}
answered 2012-08-12T18:44:49.847
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. :)

answered 2012-08-12T18:34:08.870

Your Answer