Caesar Cipher and ROT13 Letter Shift Encryption in Java

⚡ Direct Answer & Key Takeaway

A Caesar Cipher shifts every alphabet character forward by a fixed key while wrapping past Z back to A. In Java, convert each letter to a 0–25 index using `ch - 'A'` for uppercase or `ch - 'a'` for lowercase, add the shift, apply `% 26`, and add back the base ASCII code. ROT13 uses a key of 13, making encryption and decryption identical operations while spaces, digits, and punctuation stay untouched.

1. Zero-Based Modulo Arithmetic for Seamless Alphabet Wraparound

Directly adding a shift value to a character like `'X' + 5` produces `93` (`']'`) rather than `'C'`, because ASCII codes after `90` hold brackets and symbols instead of letters. Translating `'A'` to `0` through `'Z'` (`25`) fixes this gap cleanly. Compute `int offset = ch - 'A'`, advance it with `(offset + key) % 26`, and restore the character via `(char) ('A' + shifted)`. Normalizing any user-entered key with `(key % 26 + 26) % 26` ensures even large or negative shifts wrap accurately inside the 26-letter alphabet.

  • Subtracting `'A'` shifts the alphabet range from `65..90` down to `0..25` for clean modulo math.
  • Normalizing `shift = (key % 26 + 26) % 26` safely supports keys larger than 26 and negative decryption keys.
  • Explicit `(char)` casting converts the resulting `int` expression back into a Java character.

2. Preserving Case Sensitivity and Non-Alphabetic Symbols

ICSE cipher questions frequently present mixed-case sentences containing commas, hyphens, or numeric years, expecting only letters to rotate. Applying `'A'` as the base offset to a lowercase letter severely corrupts the output because lowercase ASCII begins at `97` (`'a'`), thirty-two positions above uppercase `'A'`. Writing distinct `Character.isUpperCase(ch)` and `Character.isLowerCase(ch)` branches keeps capital letters capitalized and small letters lowercase throughout the sentence. Whenever neither branch matches—such as spaces, digits, or punctuation marks—copy `ch` directly into the encrypted result unchanged, preserving word spacing and sentence structure cleanly.

  • Uppercase letters use `'A'` (65) as base; lowercase letters use `'a'` (97) as base.
  • Spaces, digits (`0–9`), and punctuation (`,`, `!`, `.`) fall into the `else` branch unmodified.
  • Using `sc.nextLine()` captures the full sentence including embedded spaces before reading the integer key.

3. Why ROT13 Acts as Its Own Inverse Cipher

ROT13 is a specialized Caesar Cipher with a fixed shift of 13, splitting the 26-letter English alphabet into two symmetric halves: A–M and N–Z. Because `13 + 13 = 26`, shifting a character twice adds 26 modulo 26, which equals a zero net displacement and restores the original plaintext. For example, `'H'` (index 7) shifts to `'U'` (index 20), and shifting `'U'` again gives `(20 + 13) % 26 = 7` (`'H'`). Board papers love asking students to verify this self-inverting symmetry in Section A output-prediction questions.

  • ROT13 swaps A↔N, B↔O, ..., M↔Z in both uppercase and lowercase alphabets.
  • Applying ROT13 to `"Uryyb, VPFR 2026!"` immediately recovers `"Hello, ICSE 2026!"`.
  • Exam variations like ICSE/ISC cipher problems often validate string length (e.g., 4 to 99 characters) before encrypting.

4. BlueJ Java Program: Caesar Cipher & ROT13 String Encryption

import java.util.*;

public class CaesarCipher {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter text to encrypt: ");
        String text = sc.nextLine();
        System.out.print("Enter shift key (use 13 for ROT13): ");
        int key = sc.nextInt();
        sc.close();

        int shift = (key % 26 + 26) % 26;
        String cipher = "";

        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            if (Character.isUpperCase(ch)) {
                char enc = (char) ('A' + (ch - 'A' + shift) % 26);
                cipher += enc;
            } else if (Character.isLowerCase(ch)) {
                char enc = (char) ('a' + (ch - 'a' + shift) % 26);
                cipher += enc;
            } else {
                cipher += ch;
            }
        }

        System.out.println("Encrypted Text: " + cipher);
    }
}

Verified Console / Dry-Run Output:

Enter text to encrypt: Hello, ICSE 2026!
Enter shift key (use 13 for ROT13): 13
Encrypted Text: Uryyb, VPFR 2026!

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

VariableData TypeExam Purpose & Sample Value
textStringStores input plaintext sentence (Sample: "Hello, ICSE 2026!")
keyintStores raw shift entered by user (Sample: 13)
shiftintNormalized positive shift in 0–25 range (Sample: 13)
chcharCurrent character inspected at index i (Sample: 'H', 'e', ',')
enccharShifted character after modulo-26 wrap (Sample: 'U', 'r')
cipherStringAccumulates final encrypted text (Sample: "Uryyb, VPFR 2026!")
🎯 1-on-1 Live Mentorship & Free Study Kit

Crack ICSE Cipher & ASCII Programs Live

Walk through modulo-26 ASCII wrapping, negative decryption keys, and ISC/ICSE cipher board questions with an expert BlueJ tutor.

💬 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: Adding the shift directly (`ch + shift`) without `% 26`, which pushes letters like 'Y' or 'z' into symbols such as '^' or '~'.
  • Avoid Mistake: Using `'A'` as the base for both uppercase and lowercase characters instead of separating `'A'` (65) and `'a'` (97).
  • Avoid Mistake: Forgetting to call `sc.nextLine()` before reading the integer shift (or mixing `nextInt()` before `nextLine()`), which skips the sentence input.
  • Examiner / Mentor Tip: Always write `(char)` before `'A' + ...` because character arithmetic in Java promotes the expression to `int`.
  • Examiner / Mentor Tip: Mention the dual-base check (`'A'` for uppercase, `'a'` for lowercase) in your comments so examiners see clear ASCII handling.
  • Examiner / Mentor Tip: Test your BlueJ program with boundary letters like `'A'`, `'Z'`, `'a'`, `'z'` plus digits to confirm no non-letter gets shifted.

7. Interactive Concept Check Quiz

Question: With `key = 5`, what output does the Caesar Cipher program produce for the input `"X 9"`?

8. Frequently Asked Questions

Why do we subtract 'A' before applying % 26 in Caesar Cipher?
Subtracting 'A' converts any uppercase letter from ASCII 65–90 into a zero-based index from 0 to 25. Applying % 26 wraps indices 26 and above cleanly back to 0 ('A'), and adding 'A' restores the valid ASCII character code without branching on wraparound cases.
How can the same Java program decrypt a Caesar Cipher text?
Pass a negative key such as -3 (or equivalently 26 - 3 = 23) when decrypting a Caesar Cipher. Because the formula computes `(key % 26 + 26) % 26`, negative keys normalize to a valid positive forward wrap automatically without causing negative remainder errors.
What is the difference between Caesar Cipher and ROT13?
ROT13 is a specific instance of the Caesar Cipher where the shift key equals 13. Because the English alphabet has 26 letters, shifting by 13 places twice shifts by 26 places, returning every letter back to its original character using the exact same formula.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class