A cipher obscures text. In the Caesar cipher, letters are shifted by a specified number of places in the alphabet. We reverse this by shifting each letter back.
So we cannot change their letters directly—instead, we can convert them to a character array. And then, for each letter in it, we apply the shifting logic.
This accepts a String
, and an int
that indicates how many places each character is to be shifted. It handles out-of-range characters by subtracting, or adding, 26.
String
to a char
array. This is a mutable data structure: an element can be changed.String
by converting the char
array into one. We use the String
constructor.public class Program { static String caesar(String value, int shift) { // Convert to char array. char[] buffer = value.toCharArray(); // Loop over characters. for (int i = 0; i < buffer.length; i++) { // Shift letter, moving back or forward 26 places if needed. char letter = buffer[i]; letter = (char) (letter + shift); if (letter > 'z') { letter = (char) (letter - 26); } else if (letter < 'a') { letter = (char) (letter + 26); } buffer[i] = letter; } // Return final string. return new String(buffer); } public static void main(String[] args) { // Test the cipher method. String a = "test"; System.out.println(a); System.out.println(); String b = caesar(a, 18); String c = caesar(b, -18); System.out.println(b); System.out.println(c); System.out.println(); String d = caesar(a, 1); String e = caesar(d, -1); System.out.println(d); System.out.println(e); System.out.println(); String f = "exxegoexsrgi"; String g = caesar(f, -4); System.out.println(f); System.out.println(g); } }test lwkl test uftu test exxegoexsrgi attackatonce
In testing, the caesar()
method correctly converted the Strings. It converted the String
"test" to "lwkl." And then it round-tripped the conversion.
The Caesar cipher is nearly the same as ROT13, except with Caesar, we do not rotate just 13 characters. We must additionally know (or decipher) the "offset" or "shift" value.
Espionage is part of human civilization. Even in 40 BC, messages were being intercepted. The Caesar cipher, unlike modern systems, is easy to break
—given the right knowledge.