Lesson 8 of 34 · Fundamentals
Boss: Java Caesar Cipher
Krag the Cipher Warden blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
The path out of the Fundamentals climbs to a frozen pass guarded by Krag the Cipher Warden. Krag only lets through travellers who can read and write his secret runes — messages scrambled with the ancient Caesar cipher. Build the cipher, and the pass is yours.
Battle plan
A Caesar cipher shifts every letter a fixed number of places along the alphabet. With a shift of 3, a becomes d, b becomes e… and at the end it wraps around: x becomes a, z becomes c. Decrypting is shifting back.
You already know every tool you need — they just meet here for the first time:
char c = 'c';
int pos = c - 'a'; // 2 (chars are numbers underneath)
char next = (char) ('a' + 3); // 'd'
Character.isLowerCase('q') // true
Character.isUpperCase('Q') // true
Character.isLetter('!') // false
Math.floorMod(-1, 26) // 25 — always between 0 and 25
-1 % 26 // -1 — % keeps the sign!
Subtracting 'a' turns a lowercase letter into its position 0–25, shifting and wrapping happens on that number, and adding 'a' back turns the position into a letter again. The same trick works for uppercase letters with 'A'.
Assignment
Implement three static methods in Main:
shiftLetter(char c, int shift)— shifts a single character:- lowercase letters stay lowercase and wrap within
a–z, - uppercase letters stay uppercase and wrap within
A–Z, - every other character (digits, spaces, punctuation) is returned unchanged,
shiftcan be negative or larger than 26.
- lowercase letters stay lowercase and wrap within
encrypt(String text, int shift)— returns the text with every character passed throughshiftLetter.decrypt(String text, int shift)— reversesencrypt, so thatdecrypt(encrypt(t, s), s)gives backt.
shiftLetter('a', 1) // 'b'
shiftLetter('z', 1) // 'a'
encrypt("hello", 3) // "khoor"
encrypt("Hello, World!", 13) // "Uryyb, Jbeyq!"
encrypt("abc", -1) // "zab"
decrypt("khoor", 3) // "hello"
Every passing test deals damage to Krag. Make all of them pass to cross the frozen pass.
Keep learning
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .