char to int Java

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

The int takes 4 bytes of memory and char takes 2 bytes of memory. 2 bytes memory value can be assigned to a 4 bytes value and is done implicitly by JVM. But the reverse operation, int to char requires explicit casting.

Following program on char to int does the implicit operation of char to int. Observe, the Java syntax of implicit casting,
public class Conversions
  public static void main(String args[])
    char ch = 'A';                // 2 bytes
    int i1 = ch;                  // 2 bytes to 4 bytes, implicit casting
    System.out.println("char value: " + ch);               // prints A
    System.out.println("Converted int value: " + i1);      // prints 65 (ASCII value of A)

char to int
Output screenshot of char to int Java

int i1 = ch;

The char ch is implicitly type casted to int i1. This is known as automatic promotion or widening conversion.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.