To convert an int
to a char
in Java, you can use a type-casting operator or the Character
class.
Using Type Casting:
int num = 65; char c = (char) num; System.out.println(c); // Output: A
Using Character class:
int num = 65; char c = Character.forDigit(num, 10); System.out.println(c); // Output: A
In the above example, the forDigit()
method of the Character
class takes two parameters – the integer value to convert and the radix (base) of the number system. The radix is 10 for decimal numbers.
Note that the integer value must represent a valid Unicode character code point, otherwise the resulting char
value may not be printable or recognizable.
Java int to char Example: Typecasting
Sure! Here’s an example of typecasting an int
to a char
using typecasting:
int num = 65; // ASCII code for capital letter A char c = (char) num; System.out.println("The integer value is: " + num); System.out.println("The character value is: " + c);
In this example, we have an int
variable num
that stores the integer value 65
, which is the ASCII code for the capital letter ‘A’. We then cast this int
value to a char
using the (char)
typecasting operator and store the result in the char
variable c
.
Finally, we print out both the integer and character values to the console using the println()
method of the System.out
object.
The output of this program would be:
The integer value is: 65 The character value is: A
This shows that the typecasting operation successfully converted the integer value to its corresponding character value.
Java int to char Example: Character.forDigit()
Sure! Here’s an example of converting an int
to a char
using the Character.forDigit()
method:
int num = 6; char c = Character.forDigit(num, 10); System.out.println("The integer value is: " + num); System.out.println("The character value is: " + c);
In this example, we have an int
variable num
that stores the integer value 6
. We then use the Character.forDigit()
method to convert this integer value to its corresponding character value, using a radix (or base) of 10
, since we are dealing with decimal numbers.
The resulting character value is then stored in the char
variable c
.
Finally, we print out both the integer and character values to the console using the println()
method of the System.out
object.
The output of this program would be:
The integer value is: 6 The character value is: 6
This shows that the Character.forDigit()
method successfully converted the integer value to its corresponding character value. However, note that in this case, the resulting character value is the same as the integer value, since the integer 6
corresponds to the character '6'
in the ASCII encoding.