Java String replace(), replaceFirst() & replaceAll() with Examples

The String Class Java has three types of Replace methods:

  1. replace()
  2. replaceAll()
  3. replaceFirst()

With the help of replace() function in Java, you can replace characters in your string. Lets study each Java string API functions in details:

Java String replace() Method

Java String replace() method replaces every occurrence of a given character with a new character and returns a new string. The Java replace() string method allows the replacement of a sequence of character values.


public Str replace(char oldC, char newC)


oldCh − old character

newCh − new character

Return Value

The Java replace() function returns a string by replacing oldCh with newCh.

Example of replace() in Java:

Let’s understand replace() in Java function with an example:

public class Guru99Ex1 {
    public static void main(String args[]) {
        String S1 = new String("the quick fox jumped");
        System.out.println("Original String is ': " + S1);
        System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox", "dog"));
        System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a'));



Original String is ‘: the quick fox jumped
String after replacing ‘fox’ with ‘dog’: the quick dog jumped
String after replacing all ‘t’ with ‘a’: ahe quick fox jumped

Java String Replaceall()

Java String replaceAll() method finds all occurrences of sequence of characters matching a regular expression and replaces them with the replacement string. At the end of call, a new string is returned by the function replaceAll() in Java.


public Str replaceAll(String regex, String replacement)


regx: regular expression

replacement: replacement sequence of characters


public class Guru99Ex2 {
    public static void main(String args[]) {
        String str = "Guru99 is a site providing free tutorials";
        //remove white spaces
        String str2 = str.replaceAll("\\s", "");



Java String replaceFirst()

Java String replaceFirst() method replaces ONLY the first substring which matches a given regular expression. Matching of the string starts from the beginning of a string (left to right). At the end of call, a new string is returned by the Java replaceFirst() function.


public Str replaceFirst(String rgex, String replacement)


rgex − the regular expression to which given string need to matched.

replacement − the string that replaces regular expression.

Return Value

This method returns resulting String as an output.

Example of replaceAll() in Java:

public class Guru99Ex2 {
    public static void main(String args[]) {
        String str = "This website providing free tutorials";
        //Only Replace first 's' with '9' 
        String str1 = str.replaceFirst("s", "9");


Thi9 website providing free tutorials