Topic 1.5
char and boolean
In one line
A char is a 16-bit number that stands for one character through the Unicode table, so you can do arithmetic on it. A boolean holds only true or false, and unlike in C it is not a number and never converts to or from one.
Think of it like this
A cinema where every seat has a number and every letter has a seat. The letter A always sits in seat 65, B in seat 66, a in seat 97. When Java stores the letter 'A', it actually stores the seat number 65 and looks the letter up when printing. A boolean is a light switch: on (true) or off (false), nothing in between.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Character
- A single letter, digit, symbol or space, like
A,7,?or. - Unicode
- A worldwide table that gives every character in every writing system its own number, called a code point.
- Code point
- A character's number in the Unicode table, like 65 for
A. - UTF-16 code unit
- A 16-bit piece of text. Java's
charis one code unit. Most characters need one; some, like many emoji, need two. - Escape sequence
- A backslash followed by a letter or code that stands for a special character, like
\nfor a new line. - Boolean
- A value that is either
trueorfalse. Named after the mathematician George Boole. - Promotion
- Java automatically widening a smaller type to
intbefore doing arithmetic on it. - Cast
- Writing a type in brackets, like
(char), to convert a value to that type on purpose. Topic 1.6 covers casting.
Step by step
01A char is a number with a label
Inside the computer, char letter = 'A'; stores the 16-bit number 65. When you print it, println sees the type char and prints the character with code 65. Cast to int to see the number: (int) letter is 65.
The first 128 Unicode values are the old ASCII table: digits '0'–'9' are 48–57, uppercase 'A'–'Z' are 65–90, lowercase 'a'–'z' are 97–122. Uppercase and lowercase differ by exactly 32.
02Doing maths with chars
Because a char is a number, you can add to it. But Java promotes char to int before arithmetic, so 'a' + 1 is the int 98. Cast it back to see a letter: (char) ('a' + 1) is 'b'.
The increment operators ++ and -- and compound assignments like c += 2 keep the char type, because they include a hidden cast (Topic 1.6).
A very common trick: convert a digit character to its number by subtracting '0': '7' - '0' is 55 - 48 = 7. The reverse is (char) ('0' + 7).
char c = 'a';
c++; // c is now 'b' (still a char)
int code = c + 1; // 99: arithmetic gives an int
char d = (char) (c + 1); // 'c': cast back to char
int seven = '7' - '0'; // 703The 'A' + 'B' trap
System.out.println('A' + 'B'); prints 131. Both operands are char, so + means addition (65 + 66), not joining text.
+ joins text only when at least one side is a String. Java evaluates left to right, so "" + 'A' + 'B' first makes the String "A", then "AB". But 'A' + 'B' + "" adds first and gives "131".
04Escape sequences
Some characters can't appear directly between quotes. A double quote would end the String; a backslash starts an escape. So Java gives you codes: \" for a double quote, \' for a single quote, \\ for a backslash, \n for a line break, \t for a tab.
\uXXXX names any code unit by its 4-digit hex value: '\u0041' is 'A'. Careful: the compiler translates \u escapes before anything else, even inside comments, so // see C:\users in a comment is a compile error (\u must be followed by 4 hex digits).
05The Character helper class
Character (the wrapper class for char) has tests and converters that work for every language, not only English: Character.isLetter, isDigit, isWhitespace, isUpperCase, isLetterOrDigit, toUpperCase, toLowerCase, getNumericValue.
Prefer them over manual range checks like c >= 'a' && c <= 'z', which fail for letters such as é or ß.
06boolean: only true or false
A boolean is the type of every yes/no question in your code: boolean isAdult = age >= 18;. Conditions in if, while and for must be booleans.
Java deliberately has no conversion between boolean and numbers. boolean b = 1; and int n = true; are compile errors, and so is (int) true. If you need 1/0, write it: int n = flag ? 1 : 0; (the ?: operator, Topic 2.2).
Name booleans as yes/no questions: isEmpty, hasNext, canRetry. Then if (isEmpty) reads like English, and you never write if (isEmpty == true).
07Characters that need two chars
Unicode now has over 150,000 characters, far more than 65,536. Characters above U+FFFF (most emoji, some rare scripts) are stored as a surrogate pair: two chars that only mean something together. So "😀".length() is 2.
For full-Unicode text work, use code points (String.codePointAt, String.codePoints()) rather than char. Topic 6.8 covers this properly.
Try it yourself
- 1
Print the alphabet's codes
In the first example, print
(int) 'Z',(int) 'a'and'a' - 'A'. Confirm uppercase letters are 65–90, lowercase 97–122, and the gap is 32. - 2
Predict the + puzzles
Write down what each prints, then run them:
'A' + 'B' + "","" + 'A' + 'B','A' + "B",(char) ('A' + 2).Answers:
131,AB,AB,C. - 3
Try a Caesar shift
Shift
'x'forward by 3 letters with wrap-around:(char) ('a' + ('x' - 'a' + 3) % 26). It printsa. Change 3 to other values and check.
Code & diagrams
Expected output
letter: A
code: 65
next: B
letter + 1: 66
after ++: y
'A' + 'B': 131
text first: AB
'7' - '0': 7
lower to upper: Q
unicode escape: AExpected output
Tab: after a tab
Quote: "hi"
Backslash: C:\temp
Line one
Line two
Single quote char: 'Expected output
letters=10 digits=2 spaces=2 other=1 upper=2
toUpperCase('q') = Q
getNumericValue('9') = 9Expected output
isTeen: true
hasTicket: false
can enter: false
negated: true
as number: 0
true
falseBreak it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Store a number in a boolean
Write boolean done = 0; as you might in C.
Break #2
Use double quotes for a char
Write char grade = "A";.
Break #3
Add to a char variable without a cast
Write char c = 'a'; char d = c + 1;.
Myth vs fact
Myth
A char is one byte, like in C.
Fact
Java's char is 2 bytes (16 bits) and unsigned. The 1-byte integer type is byte.
Myth
One char is always one visible character.
Fact
Characters above U+FFFF, including most emoji, take two chars (a surrogate pair). "😀".length() is 2.
Myth
true is 1 and false is 0 in Java.
Fact
They're not numbers at all. Java has no conversion between boolean and any numeric type.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
Unicode escapes (
\uXXXX) are processed in the very first translation step (JLS §3.3), before tokenizing. Sochar c = '\u000a';doesn't compile: the escape becomes a real line break inside the quotes. Use'\n'instead. - ▸
Since Java 9 (JEP 254, compact strings), a String whose characters all fit in Latin-1 is stored with one byte per character internally, halving memory for most text. The
charAPI is unchanged; the String converts on the fly. - ▸
Character.isLetter,isDigitand friends consult Unicode tables, soCharacter.isDigit('٣')(Arabic-Indic three) istrue, andCharacter.getNumericValuereturns 3 for it. Validate with an explicit'0'..'9'range check when you mean only ASCII digits. - ▸
Boolean.TRUEandBoolean.FALSEare cached;Boolean.valueOfreturns them, so never usenew Boolean(...)(deprecated in Java 9 and marked for removal in Java 16, along with the other wrapper constructors).
Remember this
- 1
charis a 16-bit unsigned type with values 0 to 65,535. Each value is a UTF-16 code unit. For all common letters, digits and symbols, onecharis one character, numbered by the Unicode standard.'A'is 65,'a'is 97,'0'is 48 (not 0). - 2
A
charliteral uses single quotes ('A'); aStringliteral uses double quotes ("A"). They're different types:char grade = "A";doesn't compile. - 3
Escape sequences write characters you can't type directly:
\nnew line,\ttab,\'single quote,\"double quote,\\backslash, and\u0041for any Unicode code unit by its hex number. Java 15 added\s(a space) for use in text blocks (Topic 6.5). - 4
Arithmetic on
char**promotes it toint**:'a' + 1is theint98, and you cast back to get'b':(char) ('a' + 1). Two chars added together are numbers too:'A' + 'B'is 131, not"AB". Put a String first ("" + 'A' + 'B') to get text. - 5
booleanhas exactly two values,trueandfalse. Comparisons (age >= 18) produce booleans, andif/whileaccept only booleans. There's noif (1)orif (count)in Java, which prevents a family of C bugs such asif (x = 5). - 6
Some characters, such as most emoji, are outside the first 65,536 Unicode values and need two
chars (a surrogate pair). So a String'slength()countschars, not visible characters. Topic 6.8 explains Unicode and code points fully.
Explain it without notes
What exactly does a char variable store, and why can you do arithmetic on it?
Why does 'A' + 'B' print 131 while "" + 'A' + 'B' prints AB?
Why does Java refuse if (count) and boolean b = 1; when C accepts them?
What is a surrogate pair, and why does it make length() misleading for some text?
Practice
Print each letter of "java" together with its Unicode number, one per line.
Convert the digit characters in "2026" into the number 2026 without using Integer.parseInt.
Write a program that turns 'h' into 'H' in two ways: with Character.toUpperCase and with arithmetic.
Trade-offs
- ↔
chararithmetic (c - '0',c - 'a') is fast and common in algorithms, but it only works for ASCII ranges;Charactermethods handle every language at a small cost. - ↔
Working with
charis simple and fast for most text; working with code points is correct for all Unicode text but more verbose. Choose code points when user-entered or international text matters.
Done when you can
I know a
charis a 16-bit unsigned UTF-16 code unit and can convert between chars and their codes.I can predict the result of char arithmetic and of
'A' + 'B'versus"" + 'A' + 'B'.I can write and read the common escape sequences.
I know
booleanhas no numeric conversion, and I name booleans as questions.I know why emoji make
length()larger than the visible character count.