Reputation:
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?
Upvotes: 2
Views: 893
Reputation: 175
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.
Upvotes: 3
Reputation: 285401
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.
Upvotes: 8
Reputation: 126
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?
Upvotes: 3
Reputation: 17422
Because String objects are, by design, immutable, so you need to create a new String to contain your changes
Upvotes: 4