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
Syntax
string.replace(target, replacement)
Parameters
| Parameter | Description |
|---|---|
targetCharSequence |
Text to find (literal). |
replacementCharSequence |
Text to put in its place. |
Return value
A new String.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.split()· Split a string around matches of a regular expression and return the parts as an array.- Java Strings · tutorial