I have a capital letter defined in a variable string, and I want to output the next and previous letters in the alphabet. For example, if the variable was equal to \'C\'>
All the answers are correct but none seem to give a full explanation so I'll try. Just like any other type, a char
is stored as a number (16-bit in Java). Unlike other non-numeric types, the mapping of the values of the stored numbers to the values of the char
s they represent are well known. This mapping is called the ASCII Table. The Java compiler treats char
s as a 16-bit number and therefore you can do the following:
System.out.print((int)'A'); // prints 65
System.out.print((char)65); // prints A
For this reason, the ++
, --
and other mathematical operations apply to char
s and provide a way to increment\decrement their values.
Note that the casting is cyclic when you exceed 16-bit:
System.out.print((char)65601); // also prints A
System.out.print((char)-65471); // also prints A
P.S. This also applies to Kotlin:
println('A'.toInt()) // prints 65
println(65.toChar()) // prints A
println(65601.toChar()) // prints A
println((-65471).toChar()) // prints A