January 5, 2010

Characters in Java

A char in Java is technically just an unsigned 16-bit number. The following code works just fine...


// 65656 - 1 - 120 = 65535, the max 16-bit unsigned range
char crazyChar = (char) 65656;
System.out.println("(char) 65656: " + crazyChar);


... and produces output "(char) 65656: x" (the ASCII/Unicode value for x is 120).

This is also perfectly legal, if not meaningful:

char crazierChar = (char) -552;

Note that casts are required for both of these snippets.

No comments:

Post a Comment