Difference between String replace() and replaceAll()

Jijoy picture Jijoy · May 31, 2012 · Viewed 224.9k times · Source

What's the difference between java.lang.String 's replace() and replaceAll() methods, other than later uses regex? For simple substitutions like, replace . with / , is there any difference?

Answer

emilan picture emilan · May 31, 2012

In java.lang.String, the replace method either takes a pair of char's or a pair of CharSequence's (of which String is a subclass, so it'll happily take a pair of String's). The replace method will replace all occurrences of a char or CharSequence. On the other hand, both String arguments to replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.