Convert int to char in java Convert int to char in java java java

Convert int to char in java


int a = 1;char b = (char) a;System.out.println(b);

will print out the char with Unicode code point 1 (start-of-heading char, which isn't printable; see this table: C0 Controls and Basic Latin, same as ASCII)

int a = '1';char b = (char) a;System.out.println(b);

will print out the char with Unicode code point 49 (one corresponding to '1')

If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.

If you want to convert an int seen as a Unicode code point, you can use Character.toChars(48) for example.


My answer is similar to jh314's answer but I'll explain a little deeper.

What you should do in this case is:

int a = 1;char b = (char)(a + '0');System.out.println(b);

Here, we used '0' because chars are actually represented by ASCII values. '0' is a char and represented by the value of 48.

We typed (a + '0') and in order to add these up, Java converted '0' to its ASCII value which is 48 and a is 1 so the sum is 49. Then what we did is:

(char)(49)

We casted int to char. ASCII equivalent of 49 is '1'. You can convert any digit to char this way and is smarter and better way than using .toString() method and then subtracting the digit by .charAt() method.


It seems like you are looking for the Character.forDigit method:

final int RADIX = 10;int i = 4;char ch = Character.forDigit(i, RADIX);System.out.println(ch); // Prints '4'

There is also a method that can convert from a char back to an int:

int i2 = Character.digit(ch, RADIX);System.out.println(i2); // Prints '4'

Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).