We can also convert integer into character in Java by adding the character '0' to the integer data type. This is similar to typecasting. The syntax for this method is: char c = (char)(num + '0');
char a = Character. forDigit(num1, 10); We have used the forDigit() method converts the specified int value into char value. Here, 10 and 16 are radix values for decimal and hexadecimal numbers respectively.
Conversion Using chars() The String API has a new method – chars() – with which we can obtain an instance of Stream from a String object. This simple API returns an instance of IntStream from the input String.
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
It depends on what you mean by "convert an int to char".
If you simply want to cast the value in the int, you can cast it using Java's typecast notation:
int i = 97; // 97 is 'a' in ASCII
char c = (char) i; // c is now 'a'
If you mean transforming the integer 1 into the character '1', you can do it like this:
if (i >= 0 && i <= 9) {
char c = Character.forDigit(i, 10);
....
}
If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String
constructor and provide a Charset
, or use InputStreamReader
with the appropriate Charset
instead.
Simply casting from int
to char
only works if you want ISO-8859-1, if you're reading bytes from a stream directly.
EDIT: If you are already using a Reader
, then casting the return value of read()
to char
is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int)
to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.
If you want to simply convert int 5 to char '5': (Only for integers 0 - 9)
int i = 5;
char c = (char) ('0' + i); // c is now '5';
Simple casting:
int a = 99;
char c = (char) a;
Is there any reason this is not working for you?
This solution works for Integer length size =1.
Integer input = 9;
Character.valueOf((char) input.toString().charAt(0))
if size >1 we need to use for loop and iterate through.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With