How to convert int to char in Java

Hello Learners, today we are going to learn how to convert int to char in java. As you may have heard before, the int and char both are the primitive data types in Java. The size of int data type is 4 bytes which is 32 bits. whereas the size of char data type is 2 bytes which is 16 bits long.

In this case, we are trying to convert a high sized data type into a small sized data type. we call it a Narrow Conversion. In such type of conversions when we try converting high sized data into a smaller one. we may loose precision and range of the data.

For converting int to char, we will use Java Type-Casting explicitly. Now let’s see the examples for a better understanding of the concept!

int n = 72;
char c = (char)n;
System.out.println(c);

OUTPUT:

H
  • Here, we used simple type-casting to convert n into char and saved it in c. So the character representation of 72 has been printed which is nothing but H.

Let’s take some more examples now.

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

OUTPUT:

1
  • When you try to convert 1 into char you will get nothing as an output. that is because the ASCII character associated with 1 is the start of a heading which is not printable obviously.
  • But in the next statement, we have added 0 to the variable because the ASCII value for 0 is 48. when we add 1 to it then it becomes 49 and the ASCII character for 49 is 1. So, 1 is printed.
int num = 8; 
char c = (char) (num + '0');
System.out.println(c);

OUTPUT :

8
  • Similarly, ASCII value for 0 is 48 and 48 + 8 = 56, the equivalent ASCII character for 56 is 8 so, 8 will get printed.
int b = '1';
System.out.println (b);
System.out.println ((char)b);

OUTPUT:

49

1
  • Here in this example, we have stored the integer value in single quotes. In the first statement, we are trying to print the integer value of b. So equivalent ASCII value is printed which is 49.
  • In the second statement, we are trying to print the character value of b. As we have already stored it in single quotes, so the number itself gets printed.

Also read: String to integer and integer to string conversion in Java

So, that’s all for now about how to convert int to char in Java. Till then Keep Learning, Keep Practicing, Keep Reading, Keep Coding!

“THINK TWICE CODE ONCE!”

Leave a Reply

Your email address will not be published. Required fields are marked *