Perfect Developer tutorial This page last modified 15 December 2004 (JAC)

Class char Quiz

1. When the character variable lastCharacter has the value `H`, which of the following expressions will be true?

  1. lastCharacter.isLetter
  2. lastCharacter.isDigit
  3. lastCharacter.isPrintable
  4. char{+lastCharacter} = `H`
  5. >lastCharacter = `I`
  6. (>lastCharacter).isLetter

Expressions 1, 3 and 4 will be true, and expression 2 false, for any implementation.
Expressions 5 and 6 will also be true provided the underlying implementation uses a reasonable character set (e.g. ASCII or Unicode).


2. You have two character variables firstChar and secondChar which are known to both represent digits (i.e. firstChar.isDigit & secondChar.isDigit is true). Which of the following expressions should you use to convert these to an integer, such that firstChar is the tens-digit and secondChar is the units-digit?

  1. 10 * firstCharacter + secondCharacter
  2. 10 * (firstCharacter - `0`) + (secondCharacter - `0`)
  3. 10 * (+firstCharacter) + (+secondCharacter)
  4. 10 * (+firstCharacter - +`0`) + (+secondCharacter - +`0`)
  5. 10 * firstCharacter.digit + secondCharacter.digit

Expression 1 is not well-formed because there is no automatic type conversion from char to int.
Expression 2 is not well-formed because there is no subtraction operator defined between operands of type char.
Expression 3 gives the wrong answer, because for common character sets, +`0` is not equal to 0.
Expression 4 will work for most character sets (including ASCII and Unicode).
Expression 5 is best as it is guaranteed to work for all character sets.