The .replace() method swaps every occurrence of a target with a replacement and returns a new string.
String original = "aabbcc";
String result = original.replace("bb", "XX");
System.out.println(result);
This prints aaXXcc. The method replaces all matches, not just the first one:
String spaced = "a-b-c-d";
String clean = spaced.replace("-", " ");
System.out.println(clean);
This prints a b c d. Every hyphen in the string becomes a space.
You can pass either single characters or full substrings. For pattern-based replacements (like replacing all digits), use .replaceAll() with a regular expression instead. Just remember that .replace() treats its arguments as plain text, while .replaceAll() interprets the first argument as a regex pattern.