Characters

     

Characters

A single character is represented in Java with the char primitive. The Unicode char occupies 16 bits or 2 bytes, stores a - z, A - Z, 0 - 9, and numerous other characters including those on your keyboard, and characters in languages such as Hebrew, Korean, Arabic, and other doublebyte characters.

char

The char stores 0 to 216-1 or 0 to 65,535

Default value is '\u0000', which is null in Unicode

You can write Unicode char values using a \u and the code number that represents the desired character. Here are some examples of Unicode values.

 

 '\u0030' is 0 '\u0039' is 9 '\u0041' is A '\u005A' is Z '\u0061' is a '\u007A' is z '\u000A' is LF (line feed will cause a compiler error) '\u000D' is CR (carriage return - will cause                 compiler error) 

A sequence of characters is represented by a java.lang.String object, not a char. And Java Strings are objects, not primitives. The char primitive is used to represent only a single character. This is different than in C and C++, in which a String is a primitive type. A char primitive may only hold one single character, and is actually a numeric type. So you use Strings to represent things like a name or a book title. You will learn a lot about Strings in Chapter 13. You can look up the codes used to represent Unicode characters at www.unicode.org.

Because the char is an integral type, it can be used in certain situations with mathematical operators. This ability allows us to "increment" a char . The following code uses the char with mathematical operators to print out the English alphabet from a to z, with each character separated by a comma.

Alphabet.java
 

 package net.javagarage.demo.primitives; /** * Prints the 26 letters of the English * alphabet. */ public class Alphabet { public static void main(String[] arg){     char letter = 'a';     //initialize two ints     int x = 1, y=26;     while (x < y){         System.out.print(letter + ",");         //use the ++ operator to increment char by 1         letter++;         x++;      } } } 

The ASCII character set corresponds to the first 127 values in the Unicode character set.

Note that in the preceding example, we use a single statement (remember that a statement is some code that is delimited by a semi- colon ) to initialize the values of two separate integers. This is legal, but some managers pooh-pooh the practice, citing that it is harder to read.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net