Skip to main content

Caesar Cipher Example in Java with Explanation | blogoncode

Caesar Cipher Program in Java for Encryption | HackerRank Solution

Caesar Cipher Program in Java for Encryption

Caesar cipher is one of the simplest encryption technique. It is also known as Shift cipher, Caesar shift.

By using Caesar cipher technique we can replace each letter in the plaintext with different one with fixed number of places. 

Example 1 :

Plaintext = abcd

n = 2

Caesar cipher = cdef

Example 2 :

Plaintext = xyz

n = 3

Caesar cipher = abc

Problem Description :

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Example :

string = Hello, how are you?

n = 1

Caesar cipher = Jgnnq, jqy ctg aqw?

See full problem description on HackerRank:

Lets jump on code...
 

import java.util.Scanner;

public class CaesarCipher {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
       
        System.out.println("Enter String");
        String str = sc.nextLine();
       
        System.out.println("Enter n");
        int n = sc.nextInt();
       
        String result = caesarCipher(str, n);
        System.out.println(result);
    }
    
    public static String caesarCipher(String str, int n) {
        char[] array = str.toCharArray();
       
        StringBuilder result = new StringBuilder();
       
        for (int i = 0; i < array.length; i++) {
       
            // Check if character in between 'a' to 'z'
            if ('a' <= array[i] && array[i] <= 'z') {
                result.append((char) (((array[i] - 'a' + n) % 26) + 'a'));
           
            // Check if character in between 'A' to 'Z'
            } else if ('A' <= array[i] && array[i] <= 'Z') {
                result.append((char) (((array[i] - 'A' + n) % 26) + 'A'));
           
            // Check if character is special character
            } else {
                result.append(array[i]);   
            }
        }

        return result.toString();
    }


}

Code Explanation :

  • In caesarCipher() method, First we traverse through all characters of given String.
  • In First if condition, check for Small alphabets, In else if check for Capital alphabets and in else condition append special characters to result because we did not need to do anything with that. 
  • First, we compute the position of the current letter in the alphabet, and for that, we take its ASCII code and subtract the ASCII code of letter a from it. 
  • Then apply n to this position.
  • Then using the modulo 26 to remain in the alphabet range. (For getting a to z in loop).
  • we retrieve the new character by adding the new position to the ASCII code of letter a. 

Output Explanation :

String = Hello, Coder.
n = 2

  • H is capital so it goes to else if condition,
    • H - 'A' = 7 | 072 - 065 = 7
    • Add n | add 2 | it becomes 9
    • Modulo 26 | 9 % 26 = 9
    • Finally add 'A' | ASCII of A | 9 + 065 = 074
    • Convert to char | J  
  • e is lowercase so it goes to if condition,
    • e - 'a' = 4 | 101 - 97 = 4
    • Add 2 | 6
    • 6 % 26 = 6
    • Add 'a' | 6 + 97 =103
    • Convert 103 to char | g

At last we have following answer = Jgnnq, Eqfgt.

Checkout ASCII codes for all alphabets :

RECOMMENDED ARTICLES :


Comments

Popular posts from this blog

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...