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.
public class Conversions
{
  public static void main(String args[])
  {
    long l1 = 65;   // 8 bytes
    // char ch = l1;   // error, 8 bytes to 2 bytes

    char ch = (char) l1;      // long is type converted to char
    
    System.out.println("long value: " + l1);             // prints 65
    System.out.println("Converted char value: " + ch);   // prints A (65 ASCII value for A)
  }
}


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 Comment

Your email address will not be published.