2

Why do I need to redefine the variable theString if I use the method replace in this code :

String theString = "I w@nt to h@ve the regul@r \"A\"!";
theString = theString.replace("@", "a");
System.out.println(theString);

Why can't I do :

theString.replace("@", "a");

and that's it?

jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    I'm beginning to think the Java designers blew it by calling this method `replace`. We seem to get this same question constantly. Maybe a different name would have made it clearer that it's returning a new string by transforming the old one. Oh well... too late... – ajb Jul 15 '14 at 00:55
  • 1
    @ajb: as long as Java students repeat to themselves over and over, "Strings are immutable, Strings are immutable", then this shouldn't be a problem. – Hovercraft Full Of Eels Jul 15 '14 at 01:55

4 Answers4

8

Strings are immutable -- you cannot change them once they have been created. There are exceptions of course, if you use reflective magic, but for the most part, they should be treated as invariants. So therefore the method replace(...) does not change the String, it can't, but rather it creates and returns a new String. So to be able to use that new String, you have to get access to its reference, and that can be done by assigning it to a String variable or even to the original String variable. This discussion gets to the heart of what is the difference between an object and a reference variable.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
4

Because String objects are, by design, immutable, so you need to create a new String to contain your changes

morgano
  • 17,210
  • 10
  • 45
  • 56
3

The posted answers mention the technical reason (strings are immutable) but neglect to mention why it is that way. See this: Why are strings immutable in many programming languages?

Community
  • 1
  • 1
  • 1
    This link contains useful additional information, but the linked [Why can't strings be mutable in Java and .NET?](http://stackoverflow.com/questions/93091/why-cant-strings-be-mutable-in-java-and-net) is even better! – Jongware Sep 21 '14 at 10:55
3

Taken from this link

In Java, String is not implemented as character arrays as in other programming languages. Instead string is implemented as instance of String class.

Strings are constants/ immutable and their values cannot be changed after they are created. If any operations that results in the string being altered are performed a new instance of String object is created and returned. This approach is done for implementation efficiency by Java.

It is recommended to use StringBuffer or StringBuilder when many changes need to be performed on the String. StringBuffer is like a String but can be modified. StringBuffer is thread safe and all the methods are synchronized. StringBuilder is equivalent to StringBuffer and is for use by single thread. Since the methods are not synchronized it is faster.

MAD
  • 165
  • 4