Toggle String Case in Java
Problem
Toggling case means flipping every letter's case — uppercase becomes lowercase and lowercase becomes uppercase — while leaving non-letters untouched.
Given a string, swap the case of every letter it contains.
Java Program
public class ToggleCase {
public static void main(String[] args) {
String str = "Hello World";
StringBuilder result = new StringBuilder();
// Flip the case of every letter; anything else is appended unchanged
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
result.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
result.append(Character.toUpperCase(c));
} else {
result.append(c);
}
}
System.out.println(result.toString());
}
}Output
Core Logic
Checking each character's case and flipping it individually, one pass through the string, builds the toggled result.
- 1
Character.isUpperCase(c)checks whether the current character is an uppercase letter. - 2If it is,
Character.toLowerCase(c)converts it to lowercase before appending. - 3
Character.isLowerCase(c)catches lowercase letters, converting them to uppercase withCharacter.toUpperCase(c). - 4Anything that's neither — spaces, digits, punctuation — is appended unchanged.
"Hello World", 'H' becomes 'h', 'e' becomes 'E', and so on, producing "hELLO wORLD".Key Point: The space between the two words falls through both case checks and gets appended as-is — toggling only ever touches actual letters.
Why: Each character is visited once and appended to a result buffer that grows to match the input length.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
public class ToggleCaseStream {
public static void main(String[] args) {
String str = "Hello World";
// Maps each character to its toggled form, then joins them back into a String
String result = str.chars()
.mapToObj(c -> Character.isUpperCase(c)
? String.valueOf(Character.toLowerCase((char) c))
: String.valueOf(Character.toUpperCase((char) c)))
.collect(Collectors.joining());
System.out.println(result);
}
}
Output
Core Logic
The same per-character toggle can be expressed as a stream — map each character to its flipped form and join the results.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.mapToObj(...)maps each code to its toggled single-characterString, using the same uppercase/lowercase checks as the loop version. - 3
.collect(Collectors.joining())concatenates all the toggled characters back into one result string.
"Hello World" character by character flips each letter's case, and Collectors.joining() reassembles "hELLO wORLD".Key Point: The ternary inside mapToObj() has to check both cases explicitly, same as the loop — streams change how the logic is expressed, not the underlying character-by-character work.
Why: Each character is mapped to its toggled form and Collectors.joining() rebuilds a result string holding all n characters.