wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes String.replace(char, char) method - not changing string permanently Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String.replace(char, char) method - not changing string permanently" Watch "String.replace(char, char) method - not changing string permanently" New topic
Author

String.replace(char, char) method - not changing string permanently

James Brooks
Gunslinger
Ranch Hand

Joined: Aug 17, 2006
Posts: 165
Hi guys,

I take it the String.replace(char, char) method not not change the string permanently? I mean, if I run the below program, what prints out on the command line is the muted string, but what appears in the JOptionPane after the replace() command is used is the original string, not modified. How can I change the string? Only by assigning it a new value completely?

Thanks!
-Patrick



Hello. My name is Inigo Montoya. You killed my father. Prepare to die.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Not only does it not change the string permanently, it doesn't change the string at all. The documentation is quite clear about this, it says about that method
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
In fact there are no methods that change a string in any way.

You can of course assign a new string to a variable, which I think is what you want to do. But that doesn't constitute changing a string, it only assigns a different string to the variable and leaves the original string unchanged.
[ April 11, 2007: Message edited by: Paul Clapham ]
James Brooks
Gunslinger
Ranch Hand

Joined: Aug 17, 2006
Posts: 165
Thanks, Paul, if it returns a string I know how to use it. So, strings really are immutable, after all...

-Patrick
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String.replace(char, char) method - not changing string permanently
 
Similar Threads
why it is printing from start?
Counting uppercase? Part 2!
sorting an array
The Game of Life - Please HELP!
How can I change the character in mid of the file