Those two lines behave identically, except for the fact that one applies to uppercase, and one to lowercase. I'll explain the uppercase operations here. Keep in mind that these char
values are treated as int
s until step 6 below.
ch = (char) ('A' + (ch - 'A' + key) % 26);
ch - 'A'
gives the initial character'sint
offset from capital-A.ch - 'A' + key
increases the offset bykey
, creating the ciphered character's offset from capital-A.(ch - 'A' + key) % 26
: the modulo here ensures that the numeric value of the ciphered character is 0-25 (for the 26 letters in the alphabet), preventing alphabet "overflow." The value of that expression is now the normalized offset of the ciphered character from capital-A.'A' + (ch - 'A' + key) % 26
adds the ciphered character's offset from capital-A to capital-A itself, resulting in the ciphered character'sint
value.(char) ('A' + (ch - 'A' + key) % 26)
casts thatint
tochar
type, resulting in the ciphered character as achar
.
This code treats the beginning of the alphabet (capital-A) as the "starting point," from which each letter's offset is measured. The offset is the character's number of letters from 'A'.
Example: To cipher "E" with a key of 6:
- Find the number of letters between "E" and capital-A. The ASCII code of A is 65, and the code of E is 69. To find E's offset from A, subtract
69 - 65 = 4
. - Add the offset and the key:
4 + 6 = 10
. This is the number of letters from A the ciphered character will be. 10 % 26 = 10
(no effect because of the small starting letter + small key)'A' + 10 = 65 + 10 = 75
results in the ASCII code of the ciphered character, 75 ('K')- Casting 75 to
char
allows it to be treated as a character, rather than anint
.