Java String replace()

Replacing a single character

Java String replace() method replaces all existing occurrences of a character in a String with another character. Syntax
String replace(char oldChar, char newChar)

Replacing char sequences

Java String replaceAll() method replaces all the substrings with the replacement String. Syntax
String replaceAll(String regex, String replacement)

Replacing first occurrence

Java String replaceFirst() method replaces the first substring that fits the specified with the replacement String. Syntax
String replaceFirst(String regex, String replacement)
Example
class TestClass{ public static void main (String[] args){ //replacing single char String str = "twinkle twinkle little star"; System.out.println(str); String output= str.replace('t','T'); System.out.println(output); //replacing all substring System.out.println(str); output = str.replaceAll("twinkle","Hi"); System.out.println(output); //replacing first substring System.out.println(str); output = str.replaceFirst("twinkle","Hi"); System.out.println(output); } }
Output
twinkle twinkle little star Twinkle Twinkle liTTle sTar twinkle twinkle little star Hi Hi little star twinkle twinkle little star Hi twinkle little star

Regular Expressions

The replaceAll() method allowed Regular Expressions to replace all occurrences of matching char sequences inside a String.

Example
class TestClass{ public static void main (String[] args){ //replacing single char String str = "twinkle 1111 twinkle 2222 little 3333 star"; System.out.println(str); String output = str.replaceAll("[a-zA-Z]+","Hi"); System.out.println(output); output = str.replaceAll("[0-9]+","Hi"); System.out.println(output); } }
Output
twinkle 1111 twinkle 2222 little 3333 star Hi 1111 Hi 2222 Hi 3333 Hi twinkle Hi twinkle Hi little Hi star

Difference between String replace() and replaceAll()

Java String replace method either takes a pair of char's or a pair of CharSequence . 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). In the case of performance, the replace() method is a bit faster than replaceAll() because the replaceAll() first compiles the regex pattern and then matches before finally replacing whereas the replace() simply matches for the provided argument and replaces.