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

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...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...