Skip to content
Advertisement

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

Is there a nicer way of converting a number to its alphabetic equivalent than this?

private String getCharForNumber(int i) {
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    if (i > 25) {
        return null;
    }
    return Character.toString(alphabet[i]);
}

Maybe something than can deal with numbers greater than 26 more elegantly too?

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement