Toggle Case
Java coding interview problem for Character Problems: Toggle Case.
Toggle Case is one of the most popular String manipulation interview questions.
Although it appears simple, it tests several important Java concepts including:
- Character Manipulation
- ASCII Values
- Character Class
- String Traversal
- StringBuilder
- Bitwise Operations
- Unicode Handling
Interviewers often ask follow-up questions such as:
- Can you solve it without using built-in methods?
- How does ASCII conversion work?
- Can you solve it using bitwise operators?
- Does your solution support Unicode?
- Which approach is the fastest?
Understanding multiple approaches prepares you for all these interview variations.
Problem Statement
Given a string,
convert every uppercase character into lowercase,
and every lowercase character into uppercase.
Non-alphabetic characters should remain unchanged.
Example 1
Input
CodeWithVenu
Output
cODEwITHvENU
Example 2
Input
Java123
Output
jAVA123
Example 3
Input
HELLO WORLD
Output
hello world
Example 4
Input
welcome@2026
Output
WELCOME@2026
What is Toggle Case?
Toggle Case means
Convert uppercase letters into lowercase letters and lowercase letters into uppercase letters.
Example
Java
Toggle
jAVA
Another Example
OpenAI
Toggle
oPENai
Why is this Question Asked in Interviews?
This problem evaluates your understanding of:
- Character Manipulation
- ASCII Values
- Character Class
- Loops
- Conditional Statements
- StringBuilder
It also introduces concepts used in:
- Text Editors
- Compilers
- Data Cleaning
- Password Utilities
- String Processing
Real-World Applications
Toggle case has many practical uses.
Text Editors
Convert selected text between uppercase and lowercase.
Password Processing
Normalize or transform passwords.
Data Cleaning
Convert imported text into a standard format.
Search Engines
Perform case-insensitive processing.
IDEs
Many editors provide Toggle Case shortcuts.
Understanding Uppercase and Lowercase
English alphabet contains
A-Z
and
a-z
Example
A
↓
a
M
↓
m
z
↓
Z
ASCII Character Conversion
ASCII stores uppercase and lowercase letters at different positions.
| Character | ASCII |
|---|---|
| A | 65 |
| B | 66 |
| C | 67 |
| ... | ... |
| Z | 90 |
| a | 97 |
| b | 98 |
| c | 99 |
| ... | ... |
| z | 122 |
Notice
a - A = 32
Similarly
b - B = 32
Every lowercase letter is exactly 32 greater than its uppercase version.
Mathematical Concept
Uppercase
A
↓
65
Lowercase
a
↓
97
Difference
97 - 65
=
32
Therefore
Uppercase → Lowercase
Character + 32
Lowercase → Uppercase
Character - 32
ASCII Visualization
Input
Java
ASCII
J
↓
74
Toggle
74 + 32
↓
106
↓
j
Another Character
a
↓
97
Toggle
97 - 32
↓
65
↓
A
Dry Run
Input
Java123
Read
J
Uppercase
↓
Convert
j
Read
a
Lowercase
↓
Convert
A
Read
v
↓
V
Read
a
↓
A
Digits
1
2
3
Remain unchanged.
Final Output
jAVA123
Approach 1 — Using Character Class (Recommended)
This is the most common and interview-friendly solution.
Java provides built-in methods inside the Character class.
Methods used:
Character.isUpperCase()
Character.isLowerCase()
Character.toUpperCase()
Character.toLowerCase()
These methods are readable, reliable, and support Unicode.
Algorithm
- Traverse every character.
- Check whether it is uppercase.
- Convert it to lowercase.
- Else check whether it is lowercase.
- Convert it to uppercase.
- Leave digits and symbols unchanged.
Java Program
public class ToggleCaseCharacter {
public static String toggleCase(String text) {
StringBuilder result =
new StringBuilder();
for (char ch : text.toCharArray()) {
if (Character.isUpperCase(ch)) {
result.append(
Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(
Character.toUpperCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(
toggleCase("CodeWithVenu"));
System.out.println(
toggleCase("Java123"));
}
}
Output
cODEwITHvENU
jAVA123
Step-by-Step Code Explanation
Create a StringBuilder.
StringBuilder result =
new StringBuilder();
Traverse every character.
for(char ch : text.toCharArray())
Check uppercase.
Character.isUpperCase(ch)
Convert
Character.toLowerCase(ch)
Check lowercase.
Character.isLowerCase(ch)
Convert
Character.toUpperCase(ch)
Otherwise
result.append(ch);
Digits and symbols remain unchanged.
Return
result.toString();
Dry Run of Character Class Approach
Input
Java
| Character | Action | Output |
|---|---|---|
| J | Lowercase | j |
| a | Uppercase | A |
| v | Uppercase | V |
| a | Uppercase | A |
Final
jAVA
Advantages
- Easy to understand.
- Unicode support.
- Readable code.
- Recommended for interviews.
- Safe for international text.
Drawbacks
- Slightly slower than direct ASCII arithmetic.
- Uses built-in methods.
Approach 2 — Using ASCII Arithmetic
Since uppercase and lowercase letters differ by 32 in ASCII,
we can convert them using simple arithmetic.
Uppercase → Lowercase
+32
Lowercase → Uppercase
-32
Algorithm
- Traverse characters.
- If character is between
'A'and'Z', add 32. - If character is between
'a'and'z', subtract 32. - Otherwise leave it unchanged.
Java Program
public class ToggleCaseASCII {
public static String toggleCase(String text) {
StringBuilder result =
new StringBuilder();
for (char ch : text.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
result.append((char) (ch + 32));
} else if (ch >= 'a' && ch <= 'z') {
result.append((char) (ch - 32));
} else {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(
toggleCase("CodeWithVenu"));
System.out.println(
toggleCase("Java123"));
}
}
Output
cODEwITHvENU
jAVA123
Step-by-Step Code Explanation
Check uppercase.
ch >= 'A' && ch <= 'Z'
Convert
(char)(ch + 32)
Check lowercase.
ch >= 'a' && ch <= 'z'
Convert
(char)(ch - 32)
Otherwise
Append the original character.
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| Character Class | O(n) | O(n) |
| ASCII Arithmetic | O(n) | O(n) |
Where
- n = Length of the string
Comparison of Approaches
| Feature | Character Class | ASCII Arithmetic |
|---|---|---|
| Interview Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Easy to Understand | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Performance | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Unicode Support | ✅ Yes | ❌ ASCII Only |
Advantages
- Both approaches run in O(n) time.
- Character Class is safe and Unicode-aware.
- ASCII Arithmetic is fast and simple for English letters.
- Both preserve digits, spaces, and symbols.
Drawbacks
- Character Class has slight method-call overhead.
- ASCII Arithmetic works only for English alphabet characters.
- Neither approach demonstrates advanced functional or bitwise techniques.
In Part 2, we'll cover:
- Approach 3 – Using StringBuilder
- Approach 4 – Using Java Streams
- Approach 5 – Using Bitwise XOR (
^ 32) (Advanced) - Unicode Considerations
- Comparison of All Approaches
- Common Interview Mistakes
- Edge Cases
- Interview Follow-up Questions
- Related Problems
- Key Takeaways
- Frequently Asked Interview Questions
- Interview Tips
Approach 3 — Using StringBuilder
StringBuilder is the preferred mutable string class in Java.
Instead of creating a new string every time,
we modify the result efficiently.
This approach is commonly used in production applications.
Why StringBuilder?
Strings in Java are immutable.
Example
String s = "Java";
s = s + " Programming";
A new String object is created.
With StringBuilder
StringBuilder sb = new StringBuilder();
characters are appended efficiently.
Algorithm
- Create a StringBuilder.
- Traverse every character.
- Toggle its case.
- Append it.
- Return the final string.
Java Program
public class ToggleCaseStringBuilder {
public static String toggleCase(String text) {
StringBuilder builder =
new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isUpperCase(ch)) {
builder.append(
Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
builder.append(
Character.toUpperCase(ch));
} else {
builder.append(ch);
}
}
return builder.toString();
}
public static void main(String[] args) {
System.out.println(
toggleCase("Java Programming"));
}
}
Output
jAVA pROGRAMMING
Advantages
- Fast.
- Memory efficient.
- Recommended for long strings.
- Widely used in production code.
Drawbacks
- Still depends on the
Characterclass for conversion.
Approach 4 — Using Java Streams
Java 8 Streams provide a functional programming solution.
Although concise,
Streams are generally slower than traditional loops because of object creation and Stream overhead.
Algorithm
- Convert the string into a stream.
- Toggle each character.
- Collect the result.
- Return the new string.
Java Program
import java.util.stream.Collectors;
public class ToggleCaseStreams {
public static String toggleCase(String text) {
return text.chars()
.mapToObj(ch -> {
char c = (char) ch;
if (Character.isUpperCase(c)) {
return String.valueOf(
Character.toLowerCase(c));
}
if (Character.isLowerCase(c)) {
return String.valueOf(
Character.toUpperCase(c));
}
return String.valueOf(c);
})
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(
toggleCase("CodeWithVenu"));
}
}
Output
cODEwITHvENU
Advantages
- Modern Java.
- Functional programming.
- Easy to chain with other Stream operations.
Drawbacks
- More overhead.
- Less readable for beginners.
- Rarely preferred in coding interviews.
Approach 5 — Using Bitwise XOR (^ 32) (Advanced)
This is one of the most interesting interview solutions.
ASCII uppercase and lowercase characters differ by exactly one bit.
Difference
A
↓
01000001
a
↓
01100001
Notice
Only one bit changes.
That bit corresponds to
32
Therefore
character ^ 32
toggles the case.
Binary Visualization
Uppercase
A
↓
01000001
XOR
00100000
Result
01100001
↓
a
Lowercase
a
↓
01100001
XOR
00100000
Result
01000001
↓
A
Algorithm
- Traverse characters.
- If alphabetic,
- Apply XOR with 32.
- Otherwise keep the character unchanged.
Java Program
public class ToggleCaseBitwise {
public static String toggleCase(String text) {
StringBuilder result =
new StringBuilder();
for (char ch : text.toCharArray()) {
if ((ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
result.append((char) (ch ^ 32));
} else {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(
toggleCase("Java123"));
System.out.println(
toggleCase("CodeWithVenu"));
}
}
Output
jAVA123
cODEwITHvENU
Advantages
- Extremely fast.
- Demonstrates bitwise operations.
- Popular advanced interview discussion.
Drawbacks
- Works only for ASCII English letters.
- Difficult for beginners.
- Not suitable for Unicode text.
Unicode Considerations
Java uses UTF-16 for String.
Examples
こんにちは
नमस्ते
ÄÖÜ
The Character class correctly supports Unicode case conversion for many scripts.
ASCII Arithmetic and Bitwise XOR only work reliably for the English alphabet (A-Z and a-z).
Edge Cases
| Input | Expected Output |
|---|---|
"" |
"" |
"a" |
A |
"A" |
a |
"123" |
123 |
"Java@2026" |
jAVA@2026 |
" " |
|
null |
Handle appropriately based on application requirements |
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| Character Class | O(n) | O(n) |
| ASCII Arithmetic | O(n) | O(n) |
| StringBuilder | O(n) | O(n) |
| Java Streams | O(n) | O(n) |
| Bitwise XOR | O(n) | O(n) |
Where:
- n = Length of the input string
Comparison of All Approaches
| Approach | Interview Friendly | Performance | Unicode Support | Best Use Case |
|---|---|---|---|---|
| Character Class | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ✅ | Recommended interview solution |
| ASCII Arithmetic | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ❌ | ASCII-only strings |
| StringBuilder | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | Production code |
| Java Streams | ⭐⭐⭐⭐ | ⭐⭐⭐ | ✅ | Modern Java applications |
| Bitwise XOR | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ❌ | Advanced interview discussion |
Common Interview Mistakes
Mistake 1
Applying ASCII arithmetic to Unicode text.
Example
Ä
Adding or subtracting 32 does not produce reliable Unicode case conversion.
Use the Character class instead.
Mistake 2
Changing digits and symbols.
Example
Java123!
Correct Output
jAVA123!
Digits and symbols should remain unchanged.
Mistake 3
Using string concatenation inside a loop.
Wrong
result = result + ch;
This creates many temporary String objects.
Use StringBuilder.
Mistake 4
Using XOR on every character.
Wrong
ch ^ 32
must only be applied to alphabetic ASCII characters.
Otherwise symbols such as
@
or
1
become invalid characters.
Mistake 5
Ignoring empty or null input.
Always validate the input before processing.
Interview Follow-up Questions
Q1. Why is Character.toUpperCase() preferred over ASCII arithmetic?
Q2. How does ASCII differ from Unicode?
Q3. Why does XOR with 32 work?
Q4. Which solution is fastest?
Q5. Which solution should be used in production?
Q6. What happens for digits and punctuation?
Q7. Does this work for international languages?
Q8. Why is StringBuilder preferred over String concatenation?
Q9. What is the time complexity?
Q10. Can this be solved in-place?
Related Problems
- Convert String to Uppercase
- Convert String to Lowercase
- Reverse a String
- Reverse Words in a String
- Remove Special Characters
- Count Uppercase and Lowercase Characters
- Character Frequency
- Check Palindrome
- Remove Duplicate Characters
Key Takeaways
- Toggle Case converts uppercase letters to lowercase and lowercase letters to uppercase.
- Character Class is the safest and most recommended approach because it supports Unicode.
- ASCII Arithmetic is simple and efficient for English letters.
- StringBuilder is the preferred mutable string implementation for performance.
- Java Streams provide a concise functional programming solution.
- Bitwise XOR (
^ 32) is an advanced optimization that works only for ASCII alphabetic characters.
Frequently Asked Interview Questions
Q1. Which solution is best for interviews?
The Character Class approach is the preferred answer because it is readable, Unicode-aware, and easy to explain.
Q2. Which approach is fastest?
For ASCII input, ASCII Arithmetic and Bitwise XOR are typically the fastest because they perform direct arithmetic or bitwise operations.
Q3. Why should I use StringBuilder?
StringBuilder avoids creating multiple temporary String objects, making it much more efficient for repeated modifications.
Q4. Does XOR work for Unicode?
No.
The XOR technique depends on the ASCII encoding of English letters and should not be used for general Unicode text.
Q5. Why do digits remain unchanged?
Digits, spaces, and symbols do not have uppercase or lowercase forms, so they should be copied to the output without modification.
Interview Tip
If an interviewer asks:
"Toggle the case of every character in a string."
Start with the Character Class solution because it is the industry-standard and most maintainable approach.
Then discuss increasingly optimized or specialized solutions:
- Character Class (recommended)
- ASCII Arithmetic (ASCII optimization)
- StringBuilder (efficient string construction)
- Java Streams (functional programming)
- Bitwise XOR (
^ 32) (advanced ASCII optimization)
Before coding, clarify requirements such as:
- Should the solution support Unicode characters?
- Should digits and punctuation remain unchanged?
- Is the input guaranteed to contain only English letters?
- How should
nullor empty strings be handled?
Discussing these trade-offs demonstrates strong Java fundamentals and interview-ready problem-solving skills.