The replace Method: Replacing Substrings
What you'll learn: How to use replace(CharSequence target, CharSequence replacement) to replace all occurrences of a substring throughout a String.
The Core Idea
While the single-character version of replace() swaps individual characters, the substring version takes two CharSequence arguments and replaces every occurrence of the target substring with the replacement substring. This is your go-to method when you need to find and replace entire words, phrases, or patterns in a String.
How It Works
The method signature is:
String replace(CharSequence target, CharSequence replacement)
Both target and replacement can be Strings (since String implements CharSequence). The method scans through the entire String, finds every non-overlapping occurrence of target, and substitutes it with replacement.
String message = "Java is fun. Java is powerful.";
String updated = message.replace("Java", "Python");
// Result: "Python is fun. Python is powerful."
Notice that all instances of "Java" were replaced. The original String message remains unchanged (remember immutability!), and updated holds the new String.
The "All Occurrences" Behavior
Unlike some methods that only replace the first match, this replace() method is exhaustive:
String path = "/usr/local/bin";
String windowsPath = path.replace("/", "\\");
// Result: "\\usr\\local\\bin"
Every forward slash is replaced with a backslash in one operation.
Case Sensitivity
The replacement is case-sensitive:
String text = "apple APPLE Apple";
String result = text.replace("apple", "orange");
// Result: "orange APPLE Apple" — only lowercase matched
Key Takeaway: Use replace(CharSequence target, CharSequence replacement) to replace all occurrences of a substring throughout a String, returning a new String with all substitutions applied.