Friday, 22 April 2011

chars and shorts: useful stuff to know?

It seems logical that the compiler should be able to automatically convert a char into a short, after-all they’re both 16 bits wide...

    char c = 'A';
   
short s;

    s = c;
    System.out.print
(s);

...but the code snippet above will not compile owing to a type mismatch. The reason for this is that a char is unsigned and can therefore have a higher positive value than a short.

This is the type of question you often get as a Java certification exam question and as a critique I can only say: does it matter? who uses a short anyway? I’ve never needed to use one: ints are fine except where you need a long.

No comments: