Java 25 (LTS) reference · String Methods

Java String replace() Method

Replace every occurrence of a character or text with another. replaceAll() uses a regular expression instead.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.replace(target, replacement)

Parameters

ParameterDescription
target
CharSequence
Text to find (literal).
replacement
CharSequence
Text to put in its place.

Return value

A new String.

Examples

Literal replacement
public class Main {
    public static void main(String[] args) {
        String s = "2026-10-24";
        System.out.println(s.replace("-", "/"));
        System.out.println("a.b.c".replace(".", ""));
    }
}

Output

2026/10/24
abc

Run this on your computer — see “Get Started” for setup.

Regex replacement with replaceAll()
public class Main {
    public static void main(String[] args) {
        String messy = "too    many   spaces";
        System.out.println(messy.replaceAll("\\s+", " "));
        System.out.println("Order 12 and 345".replaceAll("\\d+", "#"));
    }
}

Output

too many spaces
Order # and #

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?