How to Get Character from ASCII Value in Java

The challenge

Write a function which takes a number and returns the corresponding ASCII char for that value.

Example:

Ascii.getChar(65) // => 'A'

For ASCII table, you can refer to http://www.asciitable.com/

The solution in Java

public class Ascii {
  public static char getChar(int c) {
    return (char) c;
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void testChar() {
        assertEquals('7', Ascii.getChar(55));
        assertEquals('8', Ascii.getChar(56));
        assertEquals('9', Ascii.getChar(57));
        assertEquals(':', Ascii.getChar(58));
        assertEquals(';', Ascii.getChar(59));
        assertEquals('<', Ascii.getChar(60));
        assertEquals('=', Ascii.getChar(61));
        assertEquals('>', Ascii.getChar(62));
        assertEquals('?', Ascii.getChar(63));
        assertEquals('@', Ascii.getChar(64));
        assertEquals('A', Ascii.getChar(65));
        assertEquals("getChar should return a `char`", 0, Character.compare('!', Ascii.getChar(33)));
    }
}

Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments