Start learning free

LESSON 61 OF 344 · STRINGS I

String Replace in Java: replace and replaceFirst

Lesson Read the full explanation

In Java, you can replace part of a string using the replace() method:

s.replace(old, new)          // replaces all occurrences
s.replaceFirst(regex, new)   // replaces first match

Here are some examples:

String sentence = "I love cats";
String result = sentence.replace("cats", "dogs");
System.out.println(result);  // "I love dogs"

String text = "aaa";
System.out.println(text.replace("a", "b"));  // "bbb"

replace() returns a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · STRINGS I

    String Replace in Java, explained

    What replace does

    The replace method of String swaps every occurrence of one piece of text for another and gives you the result. The call looks like s.replace(old, new): the first argument is what to look for, and the second is what to put in its place.

    String sentence = "I love cats";
    String result = sentence.replace("cats", "dogs");
    System.out.println(result);     // I love dogs
    
    String text = "aaa";
    System.out.println(text.replace("a", "b"));   // bbb
    

    It replaces all matches, not just the first, which is why "aaa" becomes "bbb". Matches are found from left to right and don't overlap, so "aaaa".replace("aa", "b") gives "bb".

    Strings are immutable

    A Java String can never be changed after it is created. replace therefore doesn't edit the original. It builds and returns a new string. This is the most common beginner mistake with the method:

    String s = "I love cats";
    s.replace("cats", "dogs");        // result thrown away
    System.out.println(s);            // I love cats
    
    s = s.replace("cats", "dogs");    // keep the result
    System.out.println(s);            // I love dogs
    

    The first call computes the new string and then discards it. To keep the change, assign the result to a variable, either a new one or the same one.

    If the old text isn't found, nothing goes wrong. You get back a string with the same contents.

    Related methods

    Java offers a few close relatives, and picking the right one depends on whether you work with characters or with patterns.

    • s.replace(oldChar, newChar) works on single characters: "abc".replace('b', 'x') is "axc".
    • s.replaceFirst(regex, replacement) changes only the first match.
    • s.replaceAll(regex, replacement) changes all matches.

    The difference between replace and the other two is the first argument. replace treats it as plain text. replaceFirst and replaceAll treat it as a regular expression, a pattern language in which characters like . and $ have special meanings. That changes the outcome:

    System.out.println("a.b.c".replace(".", "-"));      // a-b-c
    System.out.println("a.b.c".replaceAll(".", "-"));   // -----
    System.out.println("a1b22".replaceFirst("[0-9]+", "#"));   // a#b22
    

    In a regular expression, . means "any character", so replaceAll(".", "-") turns every character into a dash. If you only want to swap literal text, use replace.

    Everyday uses

    Most real uses of replace are small cleanups: changing a separator, or removing one altogether.

    String date = "2024-10-14";
    System.out.println(date.replace("-", "/"));   // 2024/10/14
    System.out.println(date.replace("-", ""));    // 20241014
    System.out.println("hello".replace("l", "L")); // heLLo
    

    Each call returns a fresh string, and date itself still reads 2024-10-14 afterwards. Because the old and new text can have different lengths, the result can be shorter or longer than the original. The method only cares about finding the old text, wherever it is, and substituting the new text each time.

    One more point is that the replacement string can be empty but the search string should not be. Replacing the empty string "" inserts the new text between every character and at both ends, so "hello".replace("", "-") produces -h-e-l-l-o-. That is rarely what you want, so make sure the text you search for really holds something.

    The lesson's exercise

    The starting code has one variable:

    String sentence = "I love cats";
    

    The task is to produce a version with "cats" replaced by "dogs", in a single step:

    1. Declare a String named result below sentence. The new value is a string, so the variable has the type String.
    2. Assign it sentence.replace("cats", "dogs"). The method returns "I love dogs" and leaves sentence as it was.

    The complete code is:

    String sentence = "I love cats";
    
    String result = sentence.replace("cats", "dogs");
    

    After this runs, result holds "I love dogs" and sentence still holds "I love cats".

    Gotchas

    • It is case-sensitive. "Cat cat".replace("cat", "dog") gives "Cat dog", because the capital C doesn't match.
    • Replacing with an empty string deletes. " a b ".replace(" ", "") removes every space and gives "ab". This is different from strip(), which removes whitespace only at the two ends.
    • Chaining works. Each call returns a string, so you can write s.replace("cats", "dogs").replace("love", "like"), which gives "I like dogs".
    • Special characters in regex methods need escaping. To replace a literal dollar sign with replaceAll, write the pattern as "\\$". With replace you can pass "$" directly.

    Key takeaways

    • replace(old, new) changes every occurrence of plain text and returns a new string.
    • Strings are immutable, so you must use the returned value.
    • replaceFirst and replaceAll take regular expressions, so special characters behave differently from replace.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free