After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast int to char.
The int takes 4 bytes of memory and char takes 2 bytes of memory. Assignment of 4 bytes of memory to 2 bytes of memory requires explicit casting. Moreover, int can take negative values and char takes only positive values. char is implicitly unsigned by Designers (note: Java does not support unsigned data types and infact, unsigned is not a keyword of Java).
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like int to char requires explicit casting.
Examples of implicit casting
short x = 10; // 2 bytes
int y = x; // 2 bytes to 4 bytesbyte x = 10; // 1 byte
short y = x; // 1 byte to 2 bytes
Following program on int to char explains explicit casting. Observe the Java style of explicit casting.
public class Conversions
{
public static void main(String args[])
{
int i1 = 65; // 4 bytes
// char ch = i1; // error, 4 bytes to 2 bytes
char ch = (char) i1; // int is type converted to char
System.out.println("int value: " + i1); // prints 65
System.out.println("Converted char value: " + ch); // prints A (65 is ASCII value for A)
}
}
Output screenshot of int to char Java
char ch = i1;
The above statement raises a compilation error "possible loss of precision".
char ch = (char) i1;
The int i1 is explicitly type casted to char ch. Observe, the syntax of explicit casting. On both sides, it should be char.