Define a class to accept a string, and print the characters with the uppercase and lowercase reversed, but all the other characters should remain the same as before. EXAMPLE: INPUT : WelCoMe_2022 OUTPUT : wELcOmE_2022
Topic: Reversing the case of characters in a string
Answer
import java.util.Scanner;
class ReverseCase { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a string : "); String s = sc.nextLine();
String res = ""; char ch;
for(int i = 0; i < s.length(); i++) { ch = s.charAt(i); if(Character.isUpperCase(ch)) res = res + Character.toLowerCase(ch); else if(Character.isLowerCase(ch)) res = res + Character.toUpperCase(ch); else res = res + ch; }
System.out.println(res); } }
The three-way if / else if / else is the heart of this program, and the final else is what earns the "all other characters remain the same" mark.
Take each character in turn: uppercase - convert to lowercase and append lowercase - convert to uppercase and append anything else (digit, underscore, space, symbol) - append unchanged A common mistake is to write only two branches, which silently drops the digits and the underscore from the output.
Build the answer in a new String res rather than trying to alter s — Strings in Java are immutable, so no method can change the original in place. res = res + ch is the standard way to grow a result string.
Use nextLine() so a string containing spaces is read whole.
Trace WelCoMe_2022: W becomes w, e becomes E, l becomes L, C becomes c ... and _2022 passes through untouched, giving wELcOmE_2022 exactly as in the sample.
s String - the string entered by the user ch char - holds each character of s in turn res String - the result string built up with the case reversed i int - loop variable, the index into the string sc Scanner - object used to read input