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
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
A unique thing about string objects in java is that once created, you cannot change them. By the way of explanation, you cannot change the characters that compromise a string.
Your method cannot work with the current interface because of two reasons:
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
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();
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With