int to char Java

int to char Java

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).

byte –> short –> int –> long –> float –> double

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 bytes

byte 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.


int to char
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.

View all for 65 types of Conversions

Leave a Reply

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