2

I have a question with this below program

Please see the program below

public class Kiran {

    public static void main(String args[]) {

        String str = "Test";

        str.replace('T', 'B');

        System.out.println("The modified string is now " + str);
    }

}

What i was expecting is that , once i run this program , i should see the putput as Best , but to my surprise the output was Test .

Could anybody please tell me , why is it this way ??

Thanks in advance .

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • Why *would it change*? Please use [the documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) to provide supporting information when making a case for this counter-question. (Many "why doesn't" questions can be answered or refined by looking at the "why does/how does".) –  Jun 08 '12 at 15:16

6 Answers6

13

String are immutable in Java, which means you cannot change them. When you invoke the replace method you are actually creating a new String.

You can do the following:

String str = "Test";
str = str.replace('T', 'B');

Which is a reassignment.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
6

String.replace does not change the string content but returns the result of the replacement. You should do the following instead

str = str.replace('T', 'B');
GETah
  • 20,922
  • 7
  • 61
  • 103
2

Strings in Java are immutable - they cannot be changed. When you use a function like str.replace, rather than changing the string in-place, it returns a new String object with the change you requested made to it. This is explained in the documentation for String:

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

For future reference, the documentation for Java is incredibly thorough, and explains in detail what arguments methods expect, what they return, and what side-effects (if any) they have.

ZoFreX
  • 8,812
  • 5
  • 31
  • 51
2

String class is immutable. So whatever operation you did on a String object will return a new String object.

You must assign the result of the replace operation to a String variable, so that you can get the result.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
1

String objects are immutable in java i.e. whenever a modification is done on a String instead of modifying it a new String object is created in the memory.

The method str.replace('T', 'B') created a new String object in the heap memory but that object is not referenced by any string variable. To refer to that object you will have to assign it to your String variable:

str = str.replace('T', 'B');
Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
0

In addition to the above answers, if you are going to be modifying (adding/removing) data extensively, you will be better off using StringBuffer (thread safe) or StringBuilder (not thread safe) & cast it to String once done with the modifications.

ali haider
  • 19,175
  • 17
  • 80
  • 149