Java String replaceFirst() method example

The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).

1. String replaceFirst(String regex, String replacement) method

The String replaceFirst() method uses regular expression to find and replace the substring with replacement substring argument.

/**
* @param regex - the regular expression to which this string is to be matched
* @param replacement - the string to be substituted for the first match
*
* @return The resulting string after replacement is done
*/

public String replaceFirst(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

2. Java String replaceFirst() example

Java program to replace first occurrence of a given string or regex in string with a new substring. In given example, I am replacing first occurrence of substring “java” with upper case “JAVA” string.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String str = "Java says hello world. Java String tutorial";
        
        //Replace first occurrence of substring "Java" with "JAVA"
        String newStr = str.replaceFirst("Java", "JAVA");
        
        //Replace first occurrence of substring "a" with "A"
        String regexResult = str.replaceFirst("[a]", "A");
        
        System.out.println(newStr);
        System.out.println(regexResult);
    }
}

Program output.

JAVA says hello world. Java String tutorial
JAva says hello world. Java String tutorial

3. ‘null’ is not allowed

A 'null' is not allowed as both method arguments. It will throw NullPointerException.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String str = "Java says hello world. Java String tutorial";
        
        String newStr = str.replaceFirst("Java", null);
        
        System.out.println(newStr);
    }
}

Program output.

Exception in thread "main" java.lang.NullPointerException: replacement
	at java.util.regex.Matcher.replaceFirst(Matcher.java:999)
	at java.lang.String.replaceFirst(String.java:2165)
	at com.StringExample.main(StringExample.java:9)

In this example, we learned to replace first occurrence of character in string in Java.

Happy Learning !!

References:

Java String methods and examples
Java String Doc

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial