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'
, I would want to output 'B'
and 'D'
.
5 Answers
One way:
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);

- 30,111
- 9
- 76
- 83
-
But this code includes all char. not only letters, you will get a surprise when you will reach Z. (numbers etc..) Also, this assumes you start at a letter. – Marc May 24 '10 at 18:53
-
I took care of the A & Z situations with if statements so that the previous letter to A is Z and the next letter after Z is A. – raleighJ May 24 '10 at 19:00
Well if you mean the 'ABC' then they split into two sequences a-z and A-Z, the simplest way I think would be to use a char variable and to increment the index by one.
char letter='c';
letter++; // (letter=='d')
same goes for decrement:
char letter='c';
letter--; // (letter=='b')
thing is that the representation of the letters a-z are 97-122 and A-Z are 65-90, so if the case of the letter is important you need to pay attention to it.

- 98,904
- 14
- 127
- 179

- 10,106
- 12
- 75
- 118
If you are limited to the latin alphabet, you can use the fact that the characters in the ASCII table are ordered alphabetically, so:
System.out.println((char) ('C' + 1));
System.out.println((char) ('C' - 1));
outputs D
and B
.
What you do is add a char
and an int
, thus effectively adding the int
to the ascii code of the char
. When you cast back to char
, the ascii code is converted to a character.

- 588,226
- 146
- 1,060
- 1,140
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

- 7,045
- 2
- 50
- 56
just like this :
System.out.printf("%c\n",letter);
letter++;

- 21,252
- 9
- 60
- 109

- 1
- 5