Toggle Case Program in Java (Upper to Lower & Vice Versa)

⚡ Direct Answer & Key Takeaway

To toggle character case in Java for ICSE Section B exams, traverse the input string from index `0` to `length() - 1` using `charAt(i)`. Test each character with `Character.isUpperCase(ch)` and `Character.isLowerCase(ch)`—or ASCII code bounds (`65–90` and `97–122`). Convert uppercase letters to lowercase via `Character.toLowerCase(ch)`, lowercase letters to uppercase via `Character.toUpperCase(ch)`, and append digits, spaces, and punctuation marks completely unchanged into the final output string.

1. Character Wrapper Class vs. ASCII Offset Arithmetic

In CISCE Computer Applications, students can invert letter case using either `java.lang.Character` helper methods (`isUpperCase`, `isLowerCase`, `toUpperCase`, `toLowerCase`) or raw ASCII offset arithmetic. Knowing both approaches is vital because Section B allows clean library calls, while Section A output questions frequently test numeric ASCII codes (`'A'` is `65`, `'a'` is `97`, separated by an exact gap of `32`). Because Java `String` objects are immutable, you cannot modify `str.charAt(i)` in place; instead, concatenate each converted character onto a new `String` accumulator initialized to empty quotes.

  • 'A' to 'Z' span ASCII 65 to 90; 'a' to 'z' span 97 to 122, separated by a fixed offset of 32.
  • Adding 32 and type-casting (char)(ch + 32) converts an uppercase letter to lowercase without Character methods.
  • Character.toUpperCase(ch) safely leaves non-alphabetic characters unchanged, preventing symbol corruption.
  • String immutability requires building the toggled output inside a separate String variable such as toggled = "".

2. Step-by-Step Dry Run on Mixed Input

Tracing `"BlueJ@2026"` demonstrates how the `for` loop processes mixed letters, symbols, and digits cleanly. At index `0`, `'B'` satisfies `Character.isUpperCase(ch)`, appending `'b'` to `toggled`. At indices `1`, `2`, and `3`, `'l'`, `'u'`, and `'e'` enter the `else if` branch, turning into `'L'`, `'U'`, and `'E'`. Index `4` (`'J'`) flips to `'j'`. When `i` reaches `5` through `9`, `'@'`, `'2'`, `'0'`, `'2'`, and `'6'` bypass both alphabetic branches and enter the final `else` block intact, producing `"bLUEj@2026"`. Notice how `else if` guarantees each character transforms at most once per iteration.

  • Using if ... else if ... else prevents a letter converted to lowercase from immediately re-matching the lowercase check.
  • Stopping the loop at i < str.length() avoids StringIndexOutOfBoundsException at the final index.
  • Input "BlueJ@2026" becomes "bLUEj@2026", preserving digits and special symbols untouched.

3. Scanner Input Pitfalls & CISCE Exam Presentation

A classic BlueJ exam pitfall happens when reading multi-word sentences with `sc.next()` instead of `sc.nextLine()`. Because `sc.next()` stops reading at the very first space, an input like `"ICSE Java 2026!"` loses `"Java 2026!"` completely. To earn full Section B marks, declare a descriptive class name, import `java.util.*`, prompt the user clearly, print both the original and toggled strings with clean labels, close the `Scanner`, and attach a Variable Description Table documenting every loop counter, character variable, and string accumulator used inside `main()`.

  • Always call sc.nextLine() for full-sentence inputs; sc.next() drops everything after the first whitespace.
  • Close the Scanner object with sc.close() at the end of main() as tidy BlueJ practice.
  • Reserve two minutes after coding to write a complete Variable Description Table covering every variable's type and sample value.

4. ToggleCaseString.java — BlueJ ICSE Solution

import java.util.*;

public class ToggleCaseString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        String toggled = "";
        int len = str.length();

        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (Character.isUpperCase(ch)) {
                toggled = toggled + Character.toLowerCase(ch);
            } else if (Character.isLowerCase(ch)) {
                toggled = toggled + Character.toUpperCase(ch);
            } else {
                toggled = toggled + ch;
            }
        }

        System.out.println("Original String: " + str);
        System.out.println("Toggled String : " + toggled);
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a string: ICSE Java 2026!
Original String: ICSE Java 2026!
Toggled String : icse jAVA 2026!

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
scScannerReads full sentence input from keyboard (System.in)
strStringStores original user input; sample: "ICSE Java 2026!"
toggledStringAccumulates case-inverted result; ends as "icse jAVA 2026!"
lenintHolds character count via str.length(); sample: 15
iintFor-loop index iterating from 0 to len - 1 (0 to 14)
chcharExtracts current character via str.charAt(i); e.g., 'I' -> 'i'
🎯 1-on-1 Live Mentorship & Free Study Kit

Master String Manipulation & ASCII Logic Live

Book a 1-on-1 BlueJ coding session to trace Character methods, ASCII offsets, and ICSE Section B string patterns step by step.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing two separate if statements instead of if ... else if: a converted letter immediately matches the second if condition and gets altered again or duplicated.
  • Avoid Mistake: Using sc.next() instead of sc.nextLine() for sentence inputs, which silently truncates the string at the first space.
  • Avoid Mistake: Forgetting to type-cast (char)(ch + 32) when using ASCII arithmetic, which prints integer codes like 97 instead of 'a'.
  • Examiner / Mentor Tip: If an ICSE question forbids Character library functions, swap isUpperCase(ch) for (ch >= 'A' && ch <= 'Z') and toLowerCase(ch) for (char)(ch + 32).
  • Examiner / Mentor Tip: Print both the original and toggled strings with clear labels so examiners can verify whitespace preservation immediately.
  • Examiner / Mentor Tip: Double-check loop bounds (i < len, not i <= len) during dry runs to avoid off-by-one runtime exceptions.

7. Interactive Concept Check Quiz

Question: What will be the output of toggling the case of every character in the string "BlueJ_10"?

8. Frequently Asked Questions

Can I write the toggle case program in ICSE without Character class methods?
Yes. In ICSE exams, ASCII range checks are equally valid and often asked in Section A. Check `ch >= 'A' && ch <= 'Z'` and convert using `(char)(ch + 32)`. Similarly, check `ch >= 'a' && ch <= 'z'` and convert using `(char)(ch - 32)`. Keep all other characters unchanged in the `else` branch for identical output.
Why does String concatenation inside the loop work for ICSE Board exams?
Although `StringBuilder` is faster for massive text, CISCE Class 9 and 10 syllabi focus primarily on `String` methods like `length()`, `charAt()`, and `+` concatenation. Using `toggled = toggled + ...` is completely accepted by board examiners, easy to trace in a dry run, and matches standard textbook solutions without introducing extra classes.
What happens if the input string contains numbers, spaces, or punctuation?
Numbers, spaces, and punctuation marks fail both the uppercase and lowercase checks, so control passes to the final `else` block. There, the character `ch` is appended as-is to `toggled`. As a result, `"ICSE-2026!"` becomes `"icse-2026!"`, leaving hyphens, digits, spaces, and exclamation marks completely intact.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class