Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Caesar Cipher

Updated 21 Oct 2026

The Caesar cipher is a simple way of hiding a message: every letter is replaced by the letter a fixed number of places further along the alphabet. This program, written in the main method alone, reads a sentence and a key, prints the encrypted text, and then decrypts that encrypted text to show that the original sentence comes back.

Definition

For a key $k$, every letter is shifted forward by $k$ places. After Z the alphabet wraps round to A (and after z to a). Capital letters stay capital and small letters stay small. Spaces, digits and symbols are left unchanged.

If a letter has position $p$ in the alphabet (A = 0, B = 1, ..., Z = 25), the encrypted letter has position $(p + k) \bmod 26$. Decrypting shifts back by $k$, which is the same as shifting forward by $26 - k$.

  • With $k = 3$: H becomes K, and W becomes Z.
  • With $k = 1$: Z wraps to A.
  • With $k = 25$: A becomes Z and Z becomes Y.

Decisions made in this program:

  • The key must be from 1 to 25; any other key prints INVALID KEY.
  • Letters are recognised by comparing the character with 'A' to 'Z' and 'a' to 'z', not with Character.isLetter().
  • The key is read with nextInt(), so a key that is not a whole number stops the program with an error.

Algorithm

  1. Read the sentence into text and the shift key into key. If key is not between 1 and 25, print INVALID KEY and stop.
  2. Set cipher = "". For every character ch of text:
    • a capital letter is moved key places forward, wrapping round from Z to A: add (ch - 'A' + key) % 26 + 'A';
    • a small letter is moved in the same way with 'a';
    • any other character (space, digit, symbol) is copied unchanged.
  3. To decrypt, repeat the same loop on cipher with the shift back = 26 - key, and collect the result in plain. Moving forward by 26 - key undoes a forward move by key.
  4. Print cipher as the encrypted text and plain as the decrypted text.

Program

Two for loops in main use the same rule: the first encrypts text with the shift key, the second decrypts cipher with the shift 26 - key.

import java.util.*;
public class Caesar
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String text = sc.nextLine();                    // the original sentence typed by the user
        System.out.println("Enter the shift key (1 to 25):");
        int key = sc.nextInt();                         // the shift key, 1 to 25
        if (key < 1 || key > 25)
        {
            System.out.println("INVALID KEY");
            return;
        }
        String cipher = "";                             // the encrypted text
        for (int i = 0; i < text.length(); i++)
        {
            char ch = text.charAt(i);                   // current character
            if (ch >= 'A' && ch <= 'Z')                 // capital letter
                cipher = cipher + (char) ((ch - 'A' + key) % 26 + 'A');
            else if (ch >= 'a' && ch <= 'z')            // small letter
                cipher = cipher + (char) ((ch - 'a' + key) % 26 + 'a');
            else
                cipher = cipher + ch;                   // space, digit, symbol
        }
        String plain = "";                              // the decrypted text
        int back = 26 - key;                            // shifting by 26 - key undoes the shift
        for (int i = 0; i < cipher.length(); i++)
        {
            char ch = cipher.charAt(i);
            if (ch >= 'A' && ch <= 'Z')
                plain = plain + (char) ((ch - 'A' + back) % 26 + 'A');
            else if (ch >= 'a' && ch <= 'z')
                plain = plain + (char) ((ch - 'a' + back) % 26 + 'a');
            else
                plain = plain + ch;
        }
        System.out.println("Encrypted text: " + cipher);
        System.out.println("Decrypted text: " + plain);
    }
}

Variable description table

VariableData TypePurpose
argsString[]Command line arguments of main; not used
scScannerReads the input typed by the user
textStringThe original sentence typed by the user
keyintThe shift key, 1 to 25
cipherStringThe encrypted text, built one character at a time
plainStringThe decrypted text, built one character at a time
backintThe shift used to decrypt, 26 - key
iintLoop counter over the characters (used in both loops)
chcharThe character being examined (in both loops)

Sample input and output

Sample 1

Enter a sentence:
Zebra
Enter the shift key (1 to 25):
1
Encrypted text: Afcsb
Decrypted text: Zebra

Sample 2

Enter a sentence:
Hello, World! 123
Enter the shift key (1 to 25):
3
Encrypted text: Khoor, Zruog! 123
Decrypted text: Hello, World! 123

Sample 3

Enter a sentence:
Xyz  ZEBRA zebra
Enter the shift key (1 to 25):
25
Encrypted text: Wxy  YDAQZ ydaqz
Decrypted text: Xyz  ZEBRA zebra

Sample 4

Enter a sentence:
Zebra
Enter the shift key (1 to 25):
26
INVALID KEY

One value per line

Dry run

Input Zebra with key 1. The key is valid, so the first loop runs over text with the shift key = 1.

chPosition in alphabet$(p + 1) \bmod 26$Added to ciphercipher
Z250AA
e45fAf
b12cAfc
r1718sAfcs
a01bAfcsb

So cipher = Afcsb. Now the second loop runs over cipher with the shift back = 25, since $26 - 1 = 25$.

chPosition in alphabet$(p + 25) \bmod 26$Added to plainplain
A025ZZ
f54eZe
c21bZeb
s1817rZebr
b10aZebra

The decrypted text Zebra equals the original, and the output matches the real run above.

Variations

  1. Decryption "Write a program to accept an encrypted sentence and a key and display the original sentence."
  2. Reverse alphabet cipher "Write a program to replace every letter of a sentence with the letter at the same position from the end of the alphabet."
  3. Change case "Write a program to accept a sentence and change the case of every letter."
  4. Next letter "Write a program to accept a word and replace every letter by the next letter of the alphabet."