Java String replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, replace() returns a new String in which every occurrence of a character, or of a piece of text, is replaced by another one. The original string stays unchanged, so you must use the returned value.

The search is literal: characters such as ., *, or $ mean only themselves. That makes replace the right choice for plain text; use replaceAll only when you need a regular expression.

replace() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.replace(...); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result.

Syntax

Pass two chars, or two pieces of text (any CharSequence, usually String).

java
String path  = date.replace('-', '/');         // char overload
String clean = text.replace("cats", "dogs");   // CharSequence overload
CallWhat it does
"banana".replace('a', 'o')"bonono".
"a.b.c".replace(".", "")"abc": the dot is literal.
"aaa".replace("aa", "b")"ba": matches do not overlap.

Matching runs from left to right and never overlaps. Matching is case-sensitive: replace("cats", ...) does not touch "Cats".

Library declarations
java
public String replace(char oldChar, char newChar);
public String replace(CharSequence target, CharSequence replacement);

Parameters

ParameterDescription
oldChar, newCharThe char to find and the char to put in its place.
targetThe literal text to find.
replacementThe literal text to insert; $ and \ have no special meaning.

Return Value

Return ValueDescription
StringThe text with all matches replaced. For the char overload, the same object is returned when oldChar does not occur.

Java Examples

Example 1 — Replace Single Characters

Change the separators in a date and in a version number.

java
public class ReplaceChars {
    public static void main(String[] args) {
        String date = "2026-11-19";
        String slashed = date.replace('-', '/');

        System.out.println(slashed);
        System.out.println(date);
        System.out.println("1.5.0".replace('.', '_'));
    }
}

How It Works

  1. Every match, not just the first. Both dashes in the date become slashes in a single call.
  2. The source stays the same. date still prints with dashes; the new text exists only in slashed.
  3. A dot is just a dot. With the char overload there is no regex involved, so only the two periods of "1.5.0" are replaced.

Example 2 — Replace Words and Punctuation

Swap a word everywhere, then show that a period is matched literally.

java
public class ReplaceWords {
    public static void main(String[] args) {
        String text = "I like cats. cats are great. Cats sleep a lot.";

        System.out.println(text.replace("cats", "dogs"));
        System.out.println(text.replace(".", "!"));
    }
}

How It Works

  1. Case-sensitive search. Both lowercase "cats" become "dogs", but the capitalized "Cats" is a different text and stays.
  2. Literal punctuation. replace(".", "!") changes only the three periods; with replaceAll(".", "!") every character would be replaced, because . is a regex wildcard.
  3. Two independent results. The second call starts again from the unchanged text, so it still contains "cats".

Example 3 — Empty Targets, Overlaps, and No Match

Three situations that surprise many beginners.

java
public class ReplaceEdge {
    public static void main(String[] args) {
        System.out.println("abc".replace("", "|"));
        System.out.println("aaaa".replace("aa", "b"));

        String original = "hello";
        String same = original.replace('z', 'y');
        System.out.println("unchanged object? " + (same == original));
    }
}

How It Works

  1. An empty target matches everywhere. It is found before each character and at the end, so "|" is inserted four times.
  2. Left to right, no overlap. In "aaaa" the first two a's match, then the next two, giving "bb".
  3. Nothing to replace. When oldChar does not occur, the char overload is documented to return the same object, so == is true.

Frequently Asked Questions

Yes. Both overloads replace every occurrence. Use replaceFirst() if you only want the first match replaced.
replace() matches literal text. replaceAll() interprets its first argument as a regular expression and supports $1 group references in the replacement.
No. Strings are immutable, so replace() returns a new String. Write s = s.replace("a", "b"); to keep the result.
Yes. To replace regardless of case, use replaceAll("(?i)word", "new").
Replace it with an empty string: text.replace("-", "") removes every dash.

Next: replaceAll()

Replace every regex match, with $1-style group references.

replaceAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful