Tutorials

Encryption Program in Java (Caesar Cipher)

Java program to encrypt a sentence by shifting each letter by a value the user enters, wrapping from Z back to A: the Caesar cipher, with logic and dry run.

Updated
Tutorials

Write a program to accept a sentence from the user and encrypt it by replacing each letter with the letter that comes a given number of places after it in the alphabet. If the user enters 2, A becomes C, B becomes D, and Y and Z wrap around to A and B. Spaces and punctuation stay as they are.

Example:
Enter a sentence: I love programming!
Enter the shift value: 2
Encrypted sentence: K NQXG RTQITCOOKPI!

This kind of encryption is called a Caesar cipher or shift cipher, after Julius Caesar, who used it with a shift of 3.

Logic

  1. Read the sentence and convert it to upper case, so only the letters A to Z need to be handled.
  2. For each character, check whether it is a letter.
  3. For a letter, find its position in the alphabet: ch - 'A' gives 0 for A and 25 for Z.
  4. Add the shift and take the remainder after dividing by 26, so that positions past Z wrap around to the start: (pos + n) % 26.
  5. Convert the position back to a letter with (char) ('A' + pos). Any other character is copied unchanged.

Program

import java.io.*;

class Encryption
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a sentence");
        String s = br.readLine().toUpperCase();
        System.out.println("Enter the shift value");
        int n = Integer.parseInt(br.readLine().trim()) % 26;

        String enc = "";
        for (int i = 0; i < s.length(); i++)
        {
            char ch = s.charAt(i);
            if (ch >= 'A' && ch <= 'Z')
            {
                int pos = ch - 'A';               // 0 for A ... 25 for Z
                pos = (pos + n) % 26;             // shift and wrap past Z back to A
                enc = enc + (char) ('A' + pos);
            }
            else
            {
                enc = enc + ch;                   // spaces and punctuation stay as they are
            }
        }
        System.out.println("Original sentence : " + s);
        System.out.println("Encrypted sentence: " + enc);
    }
}

Output:

Enter a sentence
xyz Zebra
Enter the shift value
3
Original sentence : XYZ ZEBRA
Encrypted sentence: ABC CHEUD

Dry run for "ZOO" with shift 2

ch   pos = ch - 'A'   (pos + 2) % 26   new letter
Z    25               1                B
O    14               16               Q
O    14               16               Q
Encrypted word: BQQ

Variable description

  • s — String — the sentence entered by the user, in upper case
  • n — int — the shift value (reduced with % 26, so a shift of 28 works like 2)
  • ch — char — the current character of the sentence
  • pos — int — position of the letter in the alphabet, from 0 to 25
  • enc — String — the encrypted sentence built so far

Points to remember

  • Without % 26, letters near the end of the alphabet turn into symbols such as [ and \ instead of wrapping to A and B.
  • Typecasting with (char) is needed because 'A' + pos is an int.
  • To decrypt, shift by 26 − n instead of n.

Practice questions

  1. Modify the program to keep lower-case letters in lower case.
  2. Write the decryption program that turns the encrypted sentence back into the original.
  3. Encrypt only the vowels in a sentence and leave the consonants unchanged.

More string programs: 10 most important string programs for ICSE Class 10 and String handling in Java for ISC Class 11.