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

ISC Practicals and Theory - Caesar Cipher (OOP)

Updated 21 Oct 2026

This program encrypts a sentence with a Caesar cipher using a class whose parameterised constructor receives the sentence and the key. A separate method shifts one character, another shifts a whole string, and encrypt() and decrypt() use them. It then decrypts the encrypted text to show that the original comes back.

Definition

In a Caesar cipher with key $k$ every letter is moved forward by $k$ places in the alphabet, wrapping Z to A and z to a. Case is kept and other characters (spaces, digits, symbols) are unchanged. A letter at position $p$ (A = 0 to Z = 25) becomes the letter at position $(p + k) \bmod 26$. Shifting back by $k$ is the same as shifting forward by $26 - k$.

  • Key 3: H becomes K.
  • Key 1: Z becomes A.

Decisions made in this program:

  • The key must be from 1 to 25; otherwise INVALID KEY is printed.
  • Letters are recognised by comparing with 'A' to 'Z' and 'a' to 'z', not with Character.isLetter().
  • The key is read with nextInt(), so a non-integer key stops the program with an error.

Algorithm

  1. main reads the sentence with nextLine() into s and the key with nextInt() into k, then creates the object with new Caesar(s, k). The constructor copies them into text and key.
  2. isValidKey() returns true if key is from 1 to 25. Otherwise main prints INVALID KEY.
  3. encrypt() returns shift(text, key). main stores it in e and prints it.
  4. shift(s, k) goes through the string with a loop and joins shiftChar(s.charAt(i), k) to the result string r for each character.
  5. shiftChar(ch, k) handles one character:
    • A capital letter returns (char)((ch - 'A' + k) % 26 + 'A').
    • A small letter returns (char)((ch - 'a' + k) % 26 + 'a').
    • Any other character is returned unchanged.
  6. decrypt(c) returns shift(c, 26 - key). main calls ob.decrypt(e) on the encrypted text and prints the result.

Program

The class Caesar keeps text and key as data members. isValidKey() checks the key, shiftChar() and shift() do the shifting, encrypt() and decrypt() return the results, and main does all the input and output.

import java.util.*;

/**
 * Class Caesar (OOP version): text and key are passed to the parameterised
 * constructor. Every letter is shifted forward by key (Z to A, z to a),
 * and the encrypted text is shifted back to show the round trip.
 */
public class Caesar
{
    String text;   // the original sentence
    int key;       // the shift key, 1 to 25

    /**
     * Parameterised constructor.
     * @param t the sentence typed by the user
     * @param k the shift key typed by the user
     */
    Caesar(String t, int k)
    {
        text = t;
        key = k;
    }

    /**
     * Validates the key.
     * @return true if key is from 1 to 25, otherwise false
     */
    boolean isValidKey()
    {
        return key >= 1 && key <= 25;
    }

    /**
     * Shifts one character forward by k places with wrap-around.
     * Case is kept; a character that is not a letter is returned unchanged.
     * Character comparisons are used instead of Character.isLetter().
     * @param ch the character to shift
     * @param k number of places to shift forward (0 to 25)
     * @return the shifted character
     */
    char shiftChar(char ch, int k)
    {
        if (ch >= 'A' && ch <= 'Z')                     // capital letter
            return (char)((ch - 'A' + k) % 26 + 'A');
        if (ch >= 'a' && ch <= 'z')                     // small letter
            return (char)((ch - 'a' + k) % 26 + 'a');
        return ch;                                      // space, digit, symbol
    }

    /**
     * Shifts every character of a string forward by k places.
     * @param s the string to shift
     * @param k number of places to shift forward (0 to 25)
     * @return the shifted string
     */
    String shift(String s, int k)
    {
        String r = "";                                  // result string
        for (int i = 0; i < s.length(); i++)
            r = r + shiftChar(s.charAt(i), k);
        return r;
    }

    /**
     * Encrypts the sentence.
     * @return the text shifted forward by key
     */
    String encrypt()
    {
        return shift(text, key);
    }

    /**
     * Decrypts an encrypted string. Shifting back by key is the same as
     * shifting forward by 26 - key.
     * @param c the encrypted text
     * @return the decrypted text
     */
    String decrypt(String c)
    {
        return shift(c, 26 - key);
    }

    /** main: reads the data, creates the object and calls the methods. */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String s = sc.nextLine();                       // sentence typed by the user
        System.out.println("Enter the shift key (1 to 25):");
        int k = sc.nextInt();                           // key typed by the user
        Caesar ob = new Caesar(s, k);
        if (ob.isValidKey())
        {
            String e = ob.encrypt();                    // encrypted text
            System.out.println("Encrypted text: " + e);
            System.out.println("Decrypted text: " + ob.decrypt(e));
        }
        else
            System.out.println("INVALID KEY");
    }
}

Variable description table

VariableData TypePurpose
textStringData member: the original sentence
keyintData member: the shift key, 1 to 25
tStringParameter of the constructor: the sentence typed by the user
kintIn the constructor: parameter, the key typed by the user. In shiftChar() and shift(): parameter, places to shift forward. In main: the key read from the keyboard
chcharParameter of shiftChar(): the character to shift
sStringIn shift(): parameter, the string to shift. In main: the sentence read from the keyboard
rStringIn shift(): the result string built so far
iintLoop counter in shift(): index of the current character
cStringParameter of decrypt(): the encrypted text
scScannerReads the sentence and the key in main
eStringIn main: the encrypted text returned by encrypt()
argsString[]Command line arguments of main (not used)
obCaesarObject created in main to call the methods

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 Hello, World! 123 with key 3. isValidKey() is true. shift("Hello, World! 123", 3) calls shiftChar() for each character.

chRuleReturned
Hcapital: $(7 + 3) \bmod 26 = 10$K
esmall: $(4 + 3) \bmod 26 = 7$h
lsmall: $(11 + 3) \bmod 26 = 14$o
lsmall: 14o
osmall: $(14 + 3) \bmod 26 = 17$r
,not a letter,
spacenot a letterspace
Wcapital: $(22 + 3) \bmod 26 = 25$Z
osmall: 17r
rsmall: $(17 + 3) \bmod 26 = 20$u
lsmall: 14o
dsmall: $(3 + 3) \bmod 26 = 6$g
!, space, 1, 2, 3not lettersunchanged

So e = Khoor, Zruog! 123. decrypt(e) shifts by $26 - 3 = 23$: for example K gives $(10 + 23) \bmod 26 = 7$, which is H, and Z gives $(25 + 23) \bmod 26 = 22$, which is W. All letters return to the original, so the decrypted text is Hello, World! 123, the same as 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."