CKTIS / Java
String.replace — literal text replacement
String.replace replaces all literal matches without regular expressions. It returns the result without changing the original.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public String replace(CharSequence target, CharSequence replacement)
public String replace(char oldChar, char newChar)String.replace, through replace(CharSequence target, CharSequence replacement), replaces all non-overlapping occurrences of target with replacement, from left to right. Both arguments are literal: . and $ have no special meaning.
String is immutable: keep the returned result. The original remains unchanged. The overload replace(char oldChar, char newChar) replaces individual char values.
Unlike replaceAll, this method does not use regular expressions. The example demonstrates literal replacement, non-overlapping matches, and the unchanged original.
Examples
public class Main {
public static void main(String[] args) {
String text = "a.b.a";
System.out.println(text.replace(".", "$"));
System.out.println("aaa".replace("aa", "b"));
System.out.println(text.replace('a', 'x'));
System.out.println(text);
}
}Result
a$b$a ba x.b.x a.b.a
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.