Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in

Posted on

Implement a decoder for the ceasar cipher in Java

Implement a decoder for the ceasar cipher - Java:

public class CaesarCipher {
   * This method decode a string with the caesar cipher.
   * @param inputString String to decode.
   * @param shift int to shift the string.
   * @return String Obtains the decoded string.
   public String decode(String inputString, int shift) {
       //Variable to store the decoded string
       String decodedString = "";
       //Loop through the string
       for (int i = 0; i < inputString.length(); i++) {
           //Get the character at the current index
           char ch = inputString.charAt(i);
           //If the character is a letter, shift it
           if (Character.isLetter(ch)) {
               //Get the uppercase version of the character
               char uppercaseCh = Character.toUpperCase(ch);
               //Shift the character by the shift amount
               char shiftedCh = (char) (uppercaseCh + shift);
               //If the shifted character is outside the range of A-Z, wrap around to A-Z
               if (shiftedCh > 'Z') {
                   shiftedCh = (char) (shiftedCh - 26);
               } else if (shiftedCh < 'A') {
                   shiftedCh = (char) (shiftedCh + 26);
               //Add the decoded character to the decoded string
               decodedString += shiftedCh;
           } else {
               //Add the character to the decoded string without shifting it
               decodedString += ch;
       //Return the decoded string
       return decodedString;

   * One Example
   public static void main(String args[]) throws IOException {

      CaesarCipher  caesarCipher= new CaesarCipher ();

      //Example 1: Decode "ABC" with shift 3 to "XYZ"

      String decodedString = caesarCipher.decode("ABC", 3);

      System.out.println("Decoded String: " + decodedString); //XYZ

      //Example 2: Decode "XYZ" with shift 3 to "ABC"

      decodedString = caesarCipher.decode("XYZ", 3);

      System.out.println("Decoded String: " + decodedString); //ABC

      //Example 3: Decode "Hello World!" with shift 5 to "Mjqqt Btwqi!"

      decodedString = caesarCipher.decode("Hello World!", 5);

      System.out.println("Decoded String: " + decodedString); //Mjqqt Btwqi!

      //Example 4: Decode "Mjqqt Btwqi!" with shift 5 to "Hello World!"

      decodedString = caesarCipher.decode("Mjqqt Btwqi!", 5);

      System.out.println("Decoded String: " + decodedString); //Hello World!

Enter fullscreen mode Exit fullscreen mode

Top comments (0)