long to char Java

long to char Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast long to char as an example.

The long takes 8 bytes of memory and char takes 2 bytes of memory. Assignment of 8 bytes of memory to 2 bytes of memory requires explicit casting. Moreover, long can take negative values and char takes only positive values.

See the order of data types to know the rules of casting.

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

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program on long to char explains explicit casting. Observe Java style of explicit casting where a long is explicitly casted to char.


long to char
Output screenshot of long to char Java

char ch = l1;

The above statement raises a compilation error "possible loss of precision".

char ch = (char) l1;

The long l1 is explicitly type casted to char ch. Observe, the syntax of explicit casting. On both sides, it should be strong>char. This is known as narrowing conversion.

View all for 65 types of Conversions

Leave a Reply

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