Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string in Java

Tags:

java

string

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

like image 818
bahar_p Avatar asked Aug 12 '12 18:08

bahar_p


People also ask

Can you edit a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

How do I replace text in a string?

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.

Can we change string content Java?

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.


2 Answers

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

like image 131
Mark Byers Avatar answered Sep 30 '22 02:09

Mark Byers


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();
    }
}
like image 22
Alex Avatar answered Sep 30 '22 02:09

Alex