What is a char?

Joe Sam Shirah

While the char type is basic to the Java language, many programmers stumble over Unicode escapes, values and conversions. The first definition should be familiar:

A 16 bit primitive data type which can contain the Unicode characters 'u0000' to 'uffff'.

In addition, a char is an unsigned integral type which can contain the values 0 - 65535; All integer operations are legal ( see The Java Language Specification 4.2.1 Integral Types and Values ).

The other part to understand is that on output, the value in a char variable is treated pretty much as an index into a character map and that character is what is actually printed or displayed. For graphical output, the char value is mapped to a glyph in the selected font. Internally, it's just a number and not limited to Unicode escapes. You can use ASCII characters, decimal, hex, octal and other representations of the same value to load the variable.

The following code prints chars initialized with different numeric represenatations and uses integer operations. The last println outputs as an int, since the result of adding two chars is an int.

public class charStuff

  public static void main( String[] args )
    char aChar[] = {
                      'A',    // character
                      65,     // decimal
                      0x41,   // hex
                      0101,   // octal
                     'u0041' // Unicode escape
    int i = 0;

    for( i = 0; i < aChar.length; i++ )
      System.out.println( aChar[ i ]++ );

    System.out.println( "-----" );
    for( i = 0; i < aChar.length; i++ )
      System.out.println( aChar[ i ] );

    System.out.println( "-----" );
    System.out.println( aChar[ 0 ] + aChar[ 1 ] );

  } // end main
}  // End class charStuff
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.