In the last tutorial, we have discussed char to int conversion. In this guide, we will see how to convert an int to a char with the help of examples.
Java int to char conversion example
To convert a higher data type to lower data type, we need to do typecasting. Since int is higher data type (4 bytes) than char (2 bytes) so we need to explicitly typecast the int for the conversion.
//implicit type casting - automatic conversion char ch = 'A'; // 2 bytes int num = ch; // 2 bytes to 4 bytes /* explicit type casting - no automatic conversion * because converting higher data type to lower data type */ int num = 100; //4 bytes char ch = (char)num; //4 bytes to 2 bytes
Lets take an example.
In the following example we have an integer number num
with the value 70 and we are converting it into a char by doing typecasting.
public class JavaExample{ public static void main(String args[]){ //integer number int num = 70; //type casting char ch = (char)num; System.out.println(ch); } }
Output:
Leave a Reply