How do I convert a number to a letter in Java?

Just make use of the ASCII representation.

private String getCharForNumber(int i) {
    return i > 0 && i < 27 ? String.valueOf((char)(i + 64)) : null;
}

Note: This assumes that i is between 1 and 26 inclusive.

You’ll have to change the condition to i > -1 && i < 26 and the increment to 65 if you want i to be zero-based.

Here is the full ASCII table, in case you need to refer to:


enter image description here


Edit:

As some folks suggested here, it’s much more readable to directly use the character 'A' instead of its ASCII code.

private String getCharForNumber(int i) {
    return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null;
}

Leave a Comment