Java Puzzler, double chars

A teaser which uses char and double

The following compiles and produces an output. Can you explain why?

char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

Here is a hint for a simpler example.

byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40

Comments

  1. Well... Duh!
    'A' is 65.
    'a' is 97

    65 * 1.5 = 97.5

    And since char is an integer...

    ReplyDelete
  2. @Aleksandr

    char isn't an integer - it's unsigned integer

    ReplyDelete
  3. Or being pedantic, char is an unsigned short. ;)

    ReplyDelete
  4. That's another java puzzler.

    JLS the 3rd edition:
    The Unicode standard was originally designed as a fixed-width 16-bit character encoding. It has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, using the hexadecimal U+n notation.

    So, it is not a 32-bit integer, in the same time it definitely more than short.

    ReplyDelete
  5. @Vladimir The String and Character classes now support "code points" which assume a String is UTF-16 encoded for characters. http://en.wikipedia.org/wiki/UTF-16

    In the case of Character there are pairs of methods.

    public static boolean isLowerCase(char ch)

    public static boolean isLowerCase(int codePoint)

    http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html


    Character.MAX_VALUE is still 65535, and char is still 16-bit, but code points use int values though as you point out, not the full range of 32-bit values. ;)

    ReplyDelete

Post a Comment

Popular posts from this blog

Why You Should Tune Code Before Your Garbage Collector

Asking multiple AI to optimise the same code

Which Doc Format is Best for AI Specifications?