5.4.4. Characters


Characters

You can think of a character as something that you can type on a keyboard. For example, 'a' is the lower case letter a and 'B' is an upper case B. A character has type char.

Each character has in integer code. For example, the code for 'a' is 97 and the code for 'B' is 66. The codes for upper case letters are consecutive, starting with 'A' = 65, and the codes for the lower case letters are also consecutive, starting with 'a' = 97.

Java uses the Unicode alphabet, which has more than 100,000 characters.


Character constants

'A'

Write characters in single-quotes.

'0'

The digits '0', '1', ... have consecutive codes 48, 49, ... Notice that the code for '0' is not 0.

'\n'

This is the newline character (code 10). It indicates the end of a line.

'\t'

This is the tab character.

'\r'

This is the carriage-return character (code 13).

'\\'

This is the backslash character. Be sure to double it.

'\"'

This is the double-quote character.


Operations on Characters

Operations on characters are found in class Characteracter.

Character.isLetter(c)

True if c is a letter.

Character.isLowerCase(c)

True if c is a lower-case letter.

Character.isUpperCase(c)

True if c is an upper-case letter.

Character.isDigit(c)

True if c is a digit.

Character.isWhiteSpace(c)

This is true if c is a white-space character (space, tab, newline, carriage-return, etc.).

Character.getNumericValue(c)

Use this to convert a digit to the number that it represents. For example, Character.getNumericValue('8') yields 8.

Character.forDigit(d)

Use this to convert a single-digit number d to a character. For example, Character.forDigit(8) yields '8'.

Character.toLowerCase(c)

This is the result of converting letter c from lower case to lower case. For example, Character.toLowerCase('Q') yields 'q'.

Character.toUpperCase(c)

This is the result of converting letter c from lower case to upper case. For example, Character.toUpperCase('q') yields 'Q'. This only works if c is a lower case letter.


Exercises

  1. Write an expresion that is true if character c is a letter. Answer

  2. Suppose that c is a digit (one of the characters '0', '1', ..., '9'). Write an expression that yields the integer that corresponds to that digit. For example, if c is '4' then your expression should yield 4. Answer