Caesar Cipher Program in Java With Output

Caesar Cipher Program in Java With Output for beginners. One of the earliest known ciphers is the “Caesar Box” or “Caesar Cipher.” Julius Caesar used it to deliver secret communications to his generals in the field when it was developed circa 100 BC. His opponent would be unable to read any of his messages if they were intercepted.

Encryption in Java

Encryption is a method of securing digital data that involves the use of one or more mathematical procedures, as well as a password or “key” to decrypt the data. The encryption procedure converts data using an algorithm that renders the original data unreadable.

StringBuffer in Java

A string buffer is similar to a String, except that it can be updated. It holds a specific character sequence, but the length and content of that sequence can be altered using certain method calls. They are thread-safe and can be used by several threads. There is a limit to how much a string buffer can hold.

For Loop to Execute Caesar Cipher Program in Java

In Java, the “for” loop is an entry-controlled loop that allows a user to iteratively run a block of the statement(s) for a set number of times. The test condition specified inside the “for” loop determines the number of iterations. The Java “for” loop is one of the most simple Java loops to grasp. Using this program we can execute Caesar Cipher Program in Java With Output.

class Main
{
public static StringBuffer encrypt(String text, int s)
{
StringBuffer solution= new StringBuffer();
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
char ch = (char)(((int)text.charAt(i) + s - 65) % 26 + 65);
solution.append(ch);
}
else
{
char ch = (char)(((int)text.charAt(i) +
s - 97) % 26 + 97);
solution.append(ch);
}
}
return solution;
}
public static void main(String[] args)
{
String text = "WELCOMETOINLARN";
int s = 4;
System.out.println("Text : " + text);
System.out.println("Shift : " + s);
System.out.println("Cipher: " + encrypt(text, s));
}
}

Output:

Text : WELCOMETOINLARN
Shift : 4
Cipher: AIPGSQIXSMRPEVR