Java String replaceFirst() Method Tutorial

In this section we will learn what the String replaceFirst() method is and how to use it in Java.

What is Java String replaceFirst() Method?

When we want to search in a string to find a substring and replace that substring with a new one, the `replaceFirst()` method is the way to go.

Note: this method only replaces the first occurrence of the substring that we’re looking for in the target string.

Java replaceFirst() Method Syntax:

public String replaceFirst(String regex, String replacement)

replaceFirst() Method Parameters:

  • The first argument of the method is a regular expression that defines the substring that we’re looking for in the target string object.

Note: Other than regular expression, the first argument can also be a simple string word or sentence or even a letter. The point is the first argument is considered as the substring that the method should search for in the target string.

  • The second argument is the substring that we want to be used as the replacement with the one that might be found in the target string.

Note: Please check the Regular Expression section if you don’t know what it is and how it works.

replaceFirst() Method Return Value:

The return value of this method is a new string value that contains the replaced substring.

Note: using this method won’t change the original string value.

replaceFirst() Method Exceptions:

This method does not throw an exception.

Example: using String replaceFirst() method

public class Simple {

    public static void main(String[] args)  {
        String w = "Goodbye World!";
        String res = w.replaceFirst("Goodbye", "Hello");
        System.out.println(res);
    }
}

Output:

Hello World!

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies