Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 201 ยท Variables and Types

Characters and Booleans

Learn how Java's char stores UTF-16 code units, do arithmetic with characters, use Character methods, handle emoji and code points, and write clear boolean expressions.

Two of Java's eight primitive types aren't ordinary numbers. A char holds one character of text, such as 'J', '7' or 'รฉ'. A boolean holds a truth value: true or false. Together they drive a huge amount of everyday code: validating passwords, parsing input, counting vowels, deciding which branch of an if to run.

Both types hide a few surprises. A char is secretly a number, so 'A' + 1 is 66, not 'B'. And some characters, including most emoji, don't fit in a single char at all. This lesson explains how characters really work in Java, the Character helper methods you'll use constantly, and how to build boolean expressions that read clearly.

char literals and escape sequences

A char literal is written with single quotes around exactly one character. Double quotes make a String, which is a different type:

Java
char grade = 'A';
char digit = '7';
char space = ' ';
String word = "A";       // a String of length 1, not a char
// char empty = '';      // error: empty character literal

Some characters can't be typed directly between quotes, so Java has escape sequences that start with a backslash:

Escape Meaning
'\n' newline (line feed)
'\t' tab
'\'' single quote
'\"' double quote (also allowed unescaped in a char)
'\\' backslash
'\r' carriage return
'\s' space (mostly used in text blocks)
'\u0041' the character with Unicode number 0041 in hex: A

The \u form lets you write any character by its Unicode number, which is useful for symbols that are hard to type: '\u00e9' is รฉ and '\u20ac' is โ‚ฌ. Escape sequences in strings are covered further in Text Blocks and Escape Sequences.

A char is a number

Under the hood, a char is a 16-bit unsigned integer from 0 to 65,535. Each number stands for a character in the Unicode standard: 65 is A, 97 is a, 48 is 0, 233 is รฉ. Because it's a number, you can use a char in arithmetic, and that's where the surprises start:

Java Characters are numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rule behind this output: when you use +, -, * or / on a char, Java first promotes it to int (see Arithmetic Operators). So letter + 1 is the int 66, and IO.println prints a number. You need a cast to turn it back into a character. The increment c++ and compound assignment c += 2 are exceptions: they include a hidden cast back to char.

'a' + 'b' is 195 (97 + 98) for the same reason. Concatenation only kicks in when one side of + is a String, which is why the "" + ... trick produces ab.

Practical character arithmetic

Character math is genuinely useful, because Unicode keeps letters and digits in order:

  • '0' to '9' are codes 48 to 57, so ch - '0' converts a digit character to its number value.
  • 'a' to 'z' are 97 to 122 and 'A' to 'Z' are 65 to 90, so ch - 'a' gives a letter's position in the alphabet (0 to 25).
  • Loops can run over characters directly: for (char ch = 'a'; ch <= 'e'; ch++).
Java Digits, letters and a tiny cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In real programs you'd parse numbers with Integer.parseInt (see Type Casting and Conversion), but the ch - '0' idiom appears everywhere in parsers, puzzles and interview questions. Building secret with += in a loop is fine for short strings; for long ones use a StringBuilder.

The Character class

Hand-written range checks like ch >= 'a' && ch <= 'z' only cover English letters. The Character wrapper class has static methods that understand all of Unicode, so they work for รฉ, รŸ, ะ– or ูฃ (an Arabic-Indic digit) too:

Method Returns
Character.isLetter(ch) true for letters in any alphabet
Character.isDigit(ch) true for decimal digits in any script
Character.isLetterOrDigit(ch) either of the above
Character.isWhitespace(ch) true for space, tab, newline and similar
Character.isUpperCase(ch), isLowerCase(ch) letter case tests
Character.toUpperCase(ch), toLowerCase(ch) the converted character
Character.getNumericValue(ch) the digit's value ('7' gives 7), or -1
Character.digit(ch, radix) the digit's value in a base, such as digit('f', 16) = 15
Character.isAlphabetic(cp) a broader letter test that works on code points
Java Classifying characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

รฉ counts as a letter, which a 'a'โ€“'z' check would have missed. When you validate user input for an international audience, prefer the Character methods over hard-coded ranges.

Character.isDigit accepts digits from many scripts, not just 0โ€“9. If a field must contain only ASCII digits (a card number or a postal code, say), check ch >= '0' && ch <= '9' explicitly.

Code points, surrogate pairs and emoji

When Java was designed in the 1990s, Unicode had fewer than 65,536 characters, so a 16-bit char seemed big enough. Today Unicode has well over 150,000 characters, including emoji, many historic scripts and rare CJK ideographs.

To fit them all, Java strings use UTF-16. Each Unicode character has a number called its code point. Characters with code points up to 65,535 take one char. Characters above that take two char values called a surrogate pair. So precisely, a char is a UTF-16 code unit, not always a whole character.

Java Emoji take two chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The string has 5 visible characters (I, space, heart, space, face) but length() reports 6, because the grinning face is a surrogate pair. Even Character.toString(face), a single emoji, has length 2. The last line lists the five code points in hex: 49 (I), 20 (space), 2764 (heart), 20 and 1f600 (the face). Code that walks a string with charAt and handles each char on its own can split emoji in half and produce garbage.

For most text (names, words, numbers in English and most European and Asian languages) one char really is one character, so you don't need to worry constantly. When you process arbitrary user text, such as counting characters for a length limit or reversing a string, work with code points: codePoints(), codePointAt, codePointCount and Character.toString(int). Even code points don't cover everything: a family emoji or a flag is several code points shown as one symbol. Encodings are explored in Character Sets and Encoding.

Booleans

A boolean holds one of two values, true or false, and it is not a number. In C you can write if (1), but Java rejects it, and you can't cast between boolean and int. That strictness catches real bugs.

Booleans usually come from comparisons and logical operators:

Java
int age = 20;
boolean isAdult = age >= 18;               // comparison: true
boolean isTeen = age >= 13 && age <= 19;   // AND: false
boolean canVote = isAdult || age >= 16;    // OR: true
boolean isMinor = !isAdult;                // NOT: false

All six comparison operators (==, !=, <, >, <=, >=) produce a boolean, and &&, || and ! combine booleans. They're covered in depth, including short-circuiting, in Comparison and Logical Operators.

Java Booleans in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note that Boolean.parseBoolean returns true only for the text true in any letter case. Everything else, including "yes", "1" and null, gives false without an error, so validate stricter input yourself.

Writing clear boolean code

A few habits make boolean code easier to read and less buggy:

  • Name booleans as yes/no questions: isEmpty, hasPermission, canRetry, shouldSave. Then if (hasPermission) reads like English.
  • Don't compare with true or false. Write if (done) instead of if (done == true), and if (!done) instead of if (done == false).
  • Return the expression directly. Instead of if (x > 0) { return true; } else { return false; }, write return x > 0;.
  • Beware = vs ==. if (done = true) compiles for a boolean variable, because it assigns true and then tests it, so the branch always runs. With other types Java's strictness catches the mistake (if (count = 5) is an error), but with booleans it can't.

Use the wrapper Boolean (capital B) only when you truly need three states, true, false and "unknown" (null), or when a collection requires an object. For everyday flags the primitive boolean is simpler and can never be null.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does IO.println('A' + 2); print?

    The char is promoted to int for arithmetic, so 'A' + 2 is 65 + 2 = 67, and an int is printed as a number. A cast, (char) ('A' + 2), would print C.
  2. 2. If char ch = '8';, what is ch - '0'?

    The digit characters have consecutive codes ('0' is 48, '8' is 56), so subtracting '0' gives the digit's numeric value, 8.
  3. 3. A string contains one emoji with a code point above U+FFFF and nothing else. What does length() return?

    Java strings are UTF-16. Code points above U+FFFF are stored as a surrogate pair of two chars, so length() is 2 while codePointCount is 1.
  4. 4. What does Boolean.parseBoolean("Yes") return?

    parseBoolean returns true only for the text "true", ignoring case. Any other text, including "Yes", gives false.
  5. 5. Given boolean done = false;, what happens with if (done = true) { IO.println("Done"); }?

    An assignment is an expression whose value is the assigned value, so the condition is true and the branch runs. That's why you should write if (done) instead of comparing with true.

Summary

  • A char holds one UTF-16 code unit in single quotes, like 'A' or '\n'; \u escapes write any character by its hex code.
  • A char is an unsigned 16-bit number: arithmetic promotes it to int, so cast back with (char). ++ and += keep the char type.
  • ch - '0' turns a digit into its value, and ch - 'a' gives a letter's position.
  • The Character class (isLetter, isDigit, isWhitespace, toUpperCase, getNumericValue) works across all of Unicode.
  • Characters above U+FFFF, such as most emoji, take two char values (a surrogate pair). Use code-point methods for arbitrary user text.
  • A boolean is true or false and never a number. Build booleans from comparisons and &&, ||, !, name them like questions, and avoid == true.

Next: Type Casting and Conversion, where you'll convert between numeric types and between numbers and strings.