Java String Program · S07
Toggle the Case of Characters in Java
Flip every uppercase letter to lowercase and every lowercase letter to uppercase, leaving digits and symbols alone. Along the way, see why the ASCII XOR trick works.
Problem Statement
Write a method that returns a new string in which every uppercase letter becomes lowercase and every lowercase letter becomes uppercase.
Digits, spaces and symbols are copied unchanged. An empty string returns an empty string.
Input/Output Examples
"Hello World"Output"hELLO wORLD"Explanation: every letter changes case; the space stays."JaVa 17!"Output"jAvA 17!"Explanation: the digits and ! are not letters, so they are copied as they are.""Output""Explanation: there is nothing to change.Visual Explanation
"JaVa 17!": each character on the top row maps to the one below it. Letters change case; everything else is copied as it is.Java strings are immutable, so the method copies the characters into a char[], changes the letters in place and builds a new string at the end. Each character is decided on its own, with no state carried between them.
Approaches
Approach 1 relies on the Character class. Approach 2 uses the ASCII table directly.
Approach 1: Character Class Methods (Recommended)
Idea: use Character.isUpperCase() and Character.isLowerCase() to decide, and the matching to...() method to convert.
- Copy the string into a
char[]withtoCharArray(). - If a character is uppercase, replace it with
Character.toLowerCase(). - If it is lowercase, replace it with
Character.toUpperCase(); leave anything else alone. - Return
new String(chars).
Time: O(n) · Space: O(n). The new string itself needs n characters.
Approach 2: ASCII XOR 32
Idea: in ASCII, an uppercase letter and its lowercase form differ only in the bit with value 32, so c ^ 32 flips the case.
- Check that the character is between
AandZoraandz. - If it is, append
(char) (c ^ 32); for example,'A'(65) becomes'a'(97). - Otherwise, append the character unchanged.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Character Class Methods (Recommended)
The Character methods understand Unicode, so letters such as é are toggled too, not only A to Z.
public class ToggleCaseCharacter {
// Swaps upper and lower case; digits, spaces and symbols stay the same
static String toggleCase(String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (Character.isUpperCase(c)) {
chars[i] = Character.toLowerCase(c);
} else if (Character.isLowerCase(c)) {
chars[i] = Character.toUpperCase(c);
}
}
return new String(chars);
}
public static void main(String[] args) {
String[] inputs = {"Hello World", "JaVa 17!", ""};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + toggleCase(text) + "\"");
}
}
}
"Hello World" -> "hELLO wORLD" "JaVa 17!" -> "jAvA 17!" "" -> ""
Time complexity: O(n) · Space complexity: O(n).
Approach 2: ASCII XOR 32
A neat trick that interviewers like to discuss, but it is correct only for English letters. The range check stops it from corrupting digits and symbols.
public class ToggleCaseXor {
// In ASCII, 'A' (65) and 'a' (97) differ only in bit 5 (value 32), so XOR 32 flips the case
static String toggleCase(String text) {
StringBuilder result = new StringBuilder(text.length());
for (char c : text.toCharArray()) {
boolean asciiLetter = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
result.append(asciiLetter ? (char) (c ^ 32) : c);
}
return result.toString();
}
public static void main(String[] args) {
String[] inputs = {"Hello World", "JaVa 17!", ""};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + toggleCase(text) + "\"");
}
}
}
"Hello World" -> "hELLO wORLD" "JaVa 17!" -> "jAvA 17!" "" -> ""
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Character Class Methods | O(n) | O(n) |
| ASCII XOR 32 | O(n) | O(n) |
Here n is the length of the string. Both approaches touch every character once and must build a new string of the same length, so the output takes O(n) space.
Interview Tips and Recommended Approach
- Remember that strings are immutable. You cannot change a character in place; work on a
char[]or aStringBuilder. - Explain the XOR trick, then its limit.
c ^ 32works only for ASCII letters; applied to'1'it would produce a different symbol. - Prefer the
Charactermethods in real code. They handle Unicode letters and make the intent obvious to a reader. - Test non-letters: digits, spaces, punctuation and an empty string must come back unchanged.
Recommended Approach: Character Class Methods
Why: it is correct for every Unicode letter, leaves non-letters untouched and is easy to read. Mention the XOR version as an ASCII-only optimisation rather than your main answer.