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:
HbecomesK. - Key 1:
ZbecomesA.
Decisions made in this program:
- The key must be from 1 to 25; otherwise
INVALID KEYis printed. - Letters are recognised by comparing with
'A'to'Z'and'a'to'z', not withCharacter.isLetter(). - The key is read with
nextInt(), so a non-integer key stops the program with an error.
Algorithm
mainreads the sentence withnextLine()intosand the key withnextInt()intok, then creates the object withnew Caesar(s, k). The constructor copies them intotextandkey.isValidKey()returnstrueifkeyis from 1 to 25. OtherwisemainprintsINVALID KEY.encrypt()returnsshift(text, key).mainstores it ineand prints it.shift(s, k)goes through the string with a loop and joinsshiftChar(s.charAt(i), k)to the result stringrfor each character.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.
- A capital letter returns
decrypt(c)returnsshift(c, 26 - key).maincallsob.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
| Variable | Data Type | Purpose |
|---|---|---|
text | String | Data member: the original sentence |
key | int | Data member: the shift key, 1 to 25 |
t | String | Parameter of the constructor: the sentence typed by the user |
k | int | In 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 |
ch | char | Parameter of shiftChar(): the character to shift |
s | String | In shift(): parameter, the string to shift. In main: the sentence read from the keyboard |
r | String | In shift(): the result string built so far |
i | int | Loop counter in shift(): index of the current character |
c | String | Parameter of decrypt(): the encrypted text |
sc | Scanner | Reads the sentence and the key in main |
e | String | In main: the encrypted text returned by encrypt() |
args | String[] | Command line arguments of main (not used) |
ob | Caesar | Object 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: ZebraSample 2
Enter a sentence:
Hello, World! 123
Enter the shift key (1 to 25):
3
Encrypted text: Khoor, Zruog! 123
Decrypted text: Hello, World! 123Sample 3
Enter a sentence:
Xyz ZEBRA zebra
Enter the shift key (1 to 25):
25
Encrypted text: Wxy YDAQZ ydaqz
Decrypted text: Xyz ZEBRA zebraSample 4
Enter a sentence:
Zebra
Enter the shift key (1 to 25):
26
INVALID KEYDry run
Input Hello, World! 123 with key 3. isValidKey() is true. shift("Hello, World! 123", 3) calls shiftChar() for each character.
ch | Rule | Returned |
|---|---|---|
H | capital: $(7 + 3) \bmod 26 = 10$ | K |
e | small: $(4 + 3) \bmod 26 = 7$ | h |
l | small: $(11 + 3) \bmod 26 = 14$ | o |
l | small: 14 | o |
o | small: $(14 + 3) \bmod 26 = 17$ | r |
, | not a letter | , |
| space | not a letter | space |
W | capital: $(22 + 3) \bmod 26 = 25$ | Z |
o | small: 17 | r |
r | small: $(17 + 3) \bmod 26 = 20$ | u |
l | small: 14 | o |
d | small: $(3 + 3) \bmod 26 = 6$ | g |
!, space, 1, 2, 3 | not letters | unchanged |
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
- Decryption "Write a program to accept an encrypted sentence and a key and display the original sentence."
- 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."
- Change case "Write a program to accept a sentence and change the case of every letter."