Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
James Brooks
Gunslinger
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Paul Clapham
Sheriff
Posts: 21152
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Paul, if it returns a string I know how to use it. So, strings really are immutable, after all...

-Patrick
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic