previous | start | next

Conversions between char and other numeric types

The char type is the same memory size as a short.

A char value can be converted to a short and the other way around as well.

However, neither is a widening conversion. Ordering including char:

      byte -> short -> int -> long -> float -> double
                       /
                      /
              char --/

      That is, char -> int is a widening conversion. So

      Ex1.
      char ch = 'A';
      int n;
      
      n = ch;  // Ok. A widening conversion.

      n = 66;
      ch = (char) n;   // narrowing conversion requires a cast

      But,

      Ex2.
      short s = 65;
      char ch;

      ch = (char) s;   // Can be converted, but not widening; reqires cast
      
      ch = 'B';
      s = (short) ch;  // Can be converted, but also not widening; reqires cast

   


previous | start | next