Compiling and running it
Save the program as CaesarCipher.java, because the file name has to match the class name. Then run these two commands in the same folder:
javac CaesarCipher.javajava CaesarCipherThe first one compiles the code and the second one runs it, printing the encrypted text. New to the cipher itself? The guide explains it without code.
How the code works
In Java a char is also a number, so you can do arithmetic on it directly: 'H' - 'A' gives 7, the letter’s place in the alphabet. Add the shift and Math.floorMod keeps the result between 0 and 25, so with a shift of 3 the letter Z lands on C.
base + index gives an int, which is why the line casts it back with (char). A StringBuilder collects the result, because adding to a String in a loop creates a new object each time.
Spaces, punctuation and digits take the else branch unchanged. The c < 128 check is there because Character.isLetter also accepts accented letters: without it, é at a shift of 3 comes out as j, which you can’t decrypt back to é.
Decrypting in Java
You don’t need a second method. Decrypting is the same shift in the other direction, so pass a negative number:
System.out.println(caesar("Khoor Zruog!", -3));// Hello World!This is why the code uses Math.floorMod. Java’s % keeps the sign of the left number, so -3 % 26 is -3 and the result is not a letter at all. Math.floorMod(-3, 26) gives 23, which takes A back to X. Python’s % already works this way, as the Python version shows.
Reading input with Scanner
Assignments often ask for a program that reads the text and shift from the keyboard. Put the import at the very top of the file and replace main with this:
import java.util.Scanner; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Text: "); String text = scanner.nextLine(); System.out.print("Shift: "); int shift = scanner.nextInt(); System.out.println(caesar(text, shift));}Read the text first. nextInt() leaves the line ending behind, so a nextLine() placed after it would return an empty string.
Breaking the cipher with brute force
An alphabet of 26 letters leaves only 25 shifts to try, so a short loop can read a message without the key. Look through the output for the line that makes sense:
public static void crack(String text) { for (int shift = 1; shift < 26; shift++) { System.out.println(shift + " " + caesar(text, -shift)); }} public static void main(String[] args) { crack("Khoor Zruog!"); // 1 Jgnnq Yqtnf! // 2 Ifmmp Xpsme! // 3 Hello World! // ...}The article on brute force attacks goes deeper, and the online solver does the same in your browser.
Other alphabets and digits
To shift anything beyond A to Z, keep the alphabet in a String and find each character with indexOf(). In this example the alphabet includes digits:
static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; public static String caesarAlphabet(String text, int shift) { StringBuilder result = new StringBuilder(); for (char c : text.toCharArray()) { int position = ALPHABET.indexOf(Character.toLowerCase(c)); if (position == -1) { result.append(c); } else { int index = Math.floorMod(position + shift, ALPHABET.length()); char next = ALPHABET.charAt(index); result.append(Character.isUpperCase(c) ? Character.toUpperCase(next) : next); } } return result.toString();} public static void main(String[] args) { System.out.println(caesarAlphabet("Room 101", 3)); // Urrp 434}The wrap-around now uses ALPHABET.length(), so you only have to change the string to support another language. Our Caesar cipher tool has ready alphabets for Polish, German, Spanish and French if you want to compare results.
Encrypting a text file
Files.readString and Files.writeString read and write a whole file in one line, using UTF-8 by default. They can fail, so main has to declare throws IOException.
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; public static void main(String[] args) throws IOException { String text = Files.readString(Path.of("message.txt")); Files.writeString(Path.of("encrypted.txt"), caesar(text, 3));}Testing your code
Put these lines in main to catch the usual bugs. Java ignores assert unless you turn it on, so run the program with java -ea CaesarCipher. If nothing is wrong, it prints OK.
assert caesar("ABC", 3).equals("DEF");assert caesar("xyz", 3).equals("abc");assert caesar("Hello, World!", 5).equals("Mjqqt, Btwqi!");assert caesar(caesar("Java", 7), -7).equals("Java");assert caesar("A", 26).equals("A");assert caesar("é", 3).equals("é");System.out.println("OK");Common mistakes
The most common one is using % for a negative shift, as described above. Another is forgetting the cast: result.append(base + index) appends the number 75 where you wanted the letter K. And compare strings in your tests with equals(), because == checks whether they are the same object.
Frequently asked questions
Which Java version do I need?
The main program works on Java 8 and newer. The file example needs Java 11, which added Files.readString. We compiled and ran the code on this page with Java 21.
Can I use this to protect real data?
No. Anyone can break it in seconds with the loop shown above. Use it to learn and for puzzles. For real data, Java has modern encryption such as AES in its javax.crypto package.
How can I check that my result is right?
Enter the same text and shift in our Caesar cipher tool and compare. You can also call the free REST API from your own tests.