Java Program - Convert Int to Char - Tutorial Kart

[Pages:3]Java Program to Convert Int to Char

Java ? Convert Int to Char

In this tutorial, we shall learn how to convert an integer value to a char value.

Firstly, we shall go through the process of narrowing primitive conversion, where we shall manually convert a value of a higher datatype to a value of lower datatype.

Secondly, we shall discuss about Character.forDigit() method, which is used to get the character representation of a number for a given radix.

Convert Int to Char ? Narrow Casting

Int is a higher datatype when compared to that of Char datatype. So, when converting a higher datatype to lower datatype, you have to manually cast char to int. This is also called narrowing casting or narrowing primitive conversion.

To manually typecast int to char, place the type of lower datatype keyword before higher datatype value in parenthesis.

In the following example, we have a variable n which is of int type. We shall typecast i to char variable c .

Java Program

/** * Java Program - Convert Int to Char */ public class IntToChar {

public static void main(String[] args) { int i = 69; char c = (char) i; System.out.println(c);

} }

Output

E

Convert Int Bits to Char ? Integer.charValue()

Character.forDigit() is a static method of Character class that returns a char value for the character determined by the digit (first argument) and radix (second argument).

In this example, we shall use Character.forDigit() method to get the representation of the digit in the given radix.

For example, the digit representation of 12 in hexa-decimal (radix 16) system is c .

Java Program

/** * Java Program - Convert Int to Char */ public class IntToChar {

public static void main(String[] args) { char c1 = Character.forDigit(12, 16); System.out.println(c1); char c2 = Character.forDigit(8, 10); System.out.println(c2);

} }

Output

c 8

Conclusion

In this Java Tutorial, we learned how to write Java programs to convert an Int to Char.

Java Tutorial Java - String to Int Java - String to Float Java - String to Double Java - String to Long

Java - String to Long Java - String to Boolean Java - Int to String Java - Int to Float Java - Int to Double Java - Int to Long Java - Int to Char Java - Float to String Java - Float to Int Java - Float to Double Java - Float to Long Java - Long to String Java - Long to Float Java - Long to Double Java - Long to Int Java - Double to String Java - Double to Float Java - Double to Int Java - Double to Long Java - Char to Int Java - Boolean to String

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download