Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
How Java's char type really works: character literals, escape sequences, the Unicode escape traps, code points vs UTF-16 code units, emojis and surrogate pairs, useful Character methods, plus the boolean type and why Java never treats numbers as true or false.
kvi5hnuCode Sprout team member12 min readOn this page
The previous article covered Java's six numeric primitive types. The remaining two are char, for characters, and boolean, for truth values. boolean is simple. char looks simple but hides one of the most misunderstood topics in Java: how text is encoded with Unicode. Understanding it now will save you from subtle bugs with accented letters, Asian scripts and emojis later.
The char Type
A char value is written in single quotes:
char letter = 'A';
char digit = '7';
char symbol = '#';
Remember the difference:
'A'(single quotes) is achar: one 16-bit value."A"(double quotes) is aString: an object containing text, here of length 1.
Internally a char is an unsigned 16-bit number, from 0 to 65,535. The letter 'A' is stored as 65, 'B' as 66, the digit '7' as 55. You can write a char with its hexadecimal code as a Unicode escape, \u followed by exactly four hex digits, from '\u0000' to '\uFFFF':
public class Solution {
public static void main(String[] args) {
char letter = 'A';
char sameLetter = '\u0041'; // Unicode escape for A
char digit = '7';
System.out.println(letter + " " + sameLetter + " " + digit);
System.out.println((int) letter); // its numeric code: 65
System.out.println((int) digit); // '7' is 55, not 7!
System.out.println(digit - '0'); // 7
char next = (char) (letter + 1);
System.out.println(next); // B
System.out.println('A' + 'B'); // 131: chars are added as numbers
System.out.println("" + 'A' + 'B'); // AB
}
}
A A 7
65
55
7
B
131
AB
Three lessons from this program:
- The character
'7'is not the number 7. Its code is 55. To turn a digit character into its numeric value, subtract'0'(or useCharacter.getNumericValue). This works because the digit characters'0'…'9'have consecutive codes 48…57. - Arithmetic on
charproduces numbers.'A' + 'B'is65 + 66 = 131, anint. To get acharback, you need a cast:(char) (letter + 1). +with aStringmeans concatenation."" + 'A' + 'B'starts with a string, so each+appends text, giving"AB". Strings get their own articles soon.
Escape Sequences
Some characters can't be typed directly inside quotes: a line break, a tab, or the quote character itself. For these, Java uses escape sequences that start with a backslash \:
| Escape | Meaning | Unicode |
|---|---|---|
\n | Line feed (new line) | \u000a |
\t | Tab | \u0009 |
\r | Carriage return | \u000d |
\b | Backspace | \u0008 |
\f | Form feed | \u000c |
\" | Double quote | \u0022 |
\' | Single quote | \u0027 |
\\ | Backslash | \u005c |
\s | Space (mainly in text blocks, to keep trailing spaces) | \u0020 |
\ + line end | In text blocks only: join this line with the next | — |
\0…\377 | Octal escape (legacy; avoid) |
public class Solution {
public static void main(String[] args) {
System.out.println("Name:\tAda\nRole:\tProgrammer");
System.out.println("She said \"hi\" and left.");
System.out.println("Path: C:\\Users\\ada");
System.out.println('\'' + " is a single quote");
}
}
Name: Ada
Role: Programmer
She said "hi" and left.
Path: C:\Users\ada
' is a single quote
Text blocks (multi-line strings written between """ delimiters) are covered in the strings articles; that's where \s and the line-joining backslash are useful.
The Unicode escape traps
\u escapes are special. Unlike all the other escapes, they are processed before the compiler even parses the code. The compiler first replaces every \uXXXX in the entire source file with its character, then reads the result. This means:
\uescapes work anywhere, not just inside quotes.String\u005B\u005D argsis a legal way to writeString[] args, because\u005Band\u005Dare[and]. (Please never do this.)"\u0022+\u0022"is not a string containing"+". The escapes become quote characters first, giving""+"", which is an empty string concatenated with an empty string.- Comments are affected too. The comment
// \u000A is a newlineis a compile error, because\u000Abecomes a real line break, so "is a newline" ends up on a new line, outside the comment. - Even
// see c:\users\adain a comment fails to compile:\usersstarts with\u, which isn't followed by four hex digits.
A curiosity: a Unicode escape may contain several us: \u00E9 and \uuu00E9 both mean é. This lets conversion tools turn non-ASCII source code into pure ASCII and back again without losing information.
Unicode: Why One char Isn't Always One Character
Before Unicode
Computers store characters as numbers, but for decades every region used its own mapping: ASCII in the US (128 characters), ISO 8859-1 for Western European languages, KOI-8 for Russian, Big5 and GB18030 for Chinese, and many more. This caused two problems:
- The same number meant different characters in different encodings, so text often turned into garbage ("mojibake") when it crossed borders.
- Encodings for languages with large character sets were variable-length: some characters took one byte, others two or more, which complicated processing.
Unicode and the original 16-bit plan
Unicode set out to give every character in every writing system one unique number. When the project started in the late 1980s, 16 bits (65,536 values) seemed far more than enough; Unicode 1.0 in 1991 used less than half of them. Java was designed from the start around 16-bit Unicode characters, a big advance at a time when most languages used 8-bit characters.
Then Unicode outgrew 16 bits, mainly because of the very large set of Chinese, Japanese and Korean ideographs, and later historic scripts, mathematical symbols and emojis. Today Unicode defines well over 150,000 characters. A 16-bit char can no longer hold every character.
Code points, planes and code units
Some terminology makes the rest clear:
- A code point is the number Unicode assigns to a character, written
U+followed by hex digits.Ais U+0041,éis U+00E9, the beer mug emoji 🍺 is U+1F37A. Code points range from U+0000 to U+10FFFF. - Code points are grouped into 17 planes of 65,536 each. Plane 0, U+0000–U+FFFF, is the Basic Multilingual Plane (BMP), holding the "classic" characters of almost all modern languages. Planes 1–16, U+10000–U+10FFFF, hold supplementary characters: emojis, rarer CJK ideographs, historic scripts, musical and mathematical symbols.
- An encoding decides how code points become bits. UTF-32 uses 32 bits per code point (simple but wasteful). UTF-8, the dominant encoding for files and the web, uses 1 to 4 bytes. UTF-16, used for Java strings, uses one or two 16-bit code units.
A Java char is one UTF-16 code unit. A BMP character fits in one char. A supplementary character needs two chars, called a surrogate pair. The two halves come from a reserved range of 2,048 values that are never used for real characters: \uD800–\uDBFF for the first ("high") surrogate and \uDC00–\uDFFF for the second ("low"). That's a clever design: looking at any single char, you can tell whether it is a complete character or half of a pair.

Even code points aren't "characters"
It gets more complex. What a reader perceives as one symbol (a grapheme) can be several code points:
- The flag of Italy 🇮🇹 is two code points, the "regional indicator" letters I (U+1F1EE) and T (U+1F1F9), so four
chars. About 250 flags are built this way. - The pirate flag 🏴☠️ combines four code points (waving black flag + zero-width joiner + skull and crossbones + a variation selector): five
chars. - Emojis with skin-tone or gender modifiers, and letters combined with separate accent marks, work similarly.
Here's what this means in code:
public class Solution {
public static void main(String[] args) {
String word = "caf\u00E9"; // café
String mug = "\uD83C\uDF7A"; // beer mug emoji, U+1F37A
String flag = "\uD83C\uDDEE\uD83C\uDDF9"; // flag of Italy: 2 code points
System.out.println(word.length() + " chars, " + word.codePointCount(0, word.length()) + " code points");
System.out.println(mug.length() + " chars, " + mug.codePointCount(0, mug.length()) + " code point");
System.out.println(flag.length() + " chars, " + flag.codePointCount(0, flag.length()) + " code points");
System.out.printf("U+%X%n", mug.codePointAt(0));
System.out.println(Character.isSurrogate(mug.charAt(0)));
System.out.println(Character.charCount(0x1F37A));
}
}
4 chars, 4 code points
2 chars, 1 code point
4 chars, 2 code points
U+1F37A
true
2
String.length() counts chars (code units), not visible characters. A single emoji has length 2, and a flag has length 4.
Useful Character methods
The Character class has static helper methods for classifying and converting characters. Many accept either a char or an int code point:
| Method | Example | Result |
|---|---|---|
Character.isLetter(c) | isLetter('é') | true |
Character.isDigit(c) | isDigit('7') | true |
Character.isLetterOrDigit(c) | isLetterOrDigit('_') | false |
Character.isWhitespace(c) | isWhitespace('\t') | true |
Character.isUpperCase(c) / isLowerCase(c) | isUpperCase('Q') | true |
Character.toUpperCase(c) / toLowerCase(c) | toUpperCase('q') | 'Q' |
Character.getNumericValue(c) | getNumericValue('7') | 7 |
Character.isSurrogate(c) | isSurrogate('\uD83C') | true |
Character.charCount(cp) | charCount(0x1F37A) | 2 |
Character.toChars(cp) | toChars(0x41) | char[] {'A'} |
Character.isJavaIdentifierStart(c) / isJavaIdentifierPart(c) | isJavaIdentifierStart('3') | false |
The last pair answers a question from the program-structure article: which characters may appear in a Java name? Java's definition of "letter", "digit" and "currency symbol" is much broader than ASCII: German umlauts, Greek π, Devanagari, currency symbols like € and connectors like _ are all allowed. In practice, stick to A–Z, a–z, 0–9 and _.
The boolean Type
The boolean type has exactly two values, the literals true and false. Booleans are the results of comparisons and logical operations, and they control if statements and loops:
public class Solution {
public static void main(String[] args) {
int age = 20;
boolean isAdult = age >= 18;
boolean hasTicket = false;
System.out.println("adult: " + isAdult);
System.out.println("may enter: " + (isAdult && hasTicket));
System.out.println(!hasTicket);
}
}
adult: true
may enter: false
true
&& means "and", and ! means "not". The operators article covers them all.
Numbers are not booleans
In C and C++, numbers and even pointers can be used as conditions: 0 counts as false and anything else as true. Java doesn't allow this. There is no conversion between integers and boolean, in either direction, not even with a cast.
This protects you from a classic C bug, writing = (assignment) instead of == (comparison):
int x = 5;
if (x = 0) { // meant: if (x == 0)
System.out.println("zero");
}
In C this compiles: it assigns 0 to x and then treats 0 as false, so the condition is silently always false. In Java it's a compile error:
Solution.java:4: error: incompatible types: int cannot be converted to boolean
if (x = 0) {
^
If you need a number from a boolean, say so explicitly: int bit = flag ? 1 : 0;.
Common questions
Can I use ++ on a char?
Yes. c++ and c += 1 include an implicit cast back to char, so char c = 'A'; c++; gives 'B'. c = c + 1 doesn't compile, because c + 1 is an int. This is the same rule as for byte and short in the conversions article.
Is "é".length() always 1?
No. It depends on how the text was written. é can be one code point (U+00E9, length 1) or the letter e followed by a combining accent (U+0301, length 2). Both look identical. Use java.text.Normalizer.normalize(s, Normalizer.Form.NFC) before comparing or counting text that comes from users or files.
Should I store text as char[] or as String?
Use String almost always. Strings are immutable, have a rich API and, since Java 9, are stored compactly (one byte per character when all characters are Latin-1). A char[] is useful only for special cases such as password fields, where you want to overwrite the contents after use.
What does (int) 'A' give, and how do I go the other way?
(int) 'A' is 65. Going back, (char) 65 is 'A'. For code points beyond the BMP, such as emojis, use Character.toChars(cp) or Character.toString(cp) (Java 11), because one char can't hold them.
Can a boolean be null?
A primitive boolean can't. It is always true or false, and fields default to false. The wrapper type Boolean can be null. Unboxing a null Boolean, for example in if (flag), throws NullPointerException.
Summary
charholds one UTF-16 code unit: a 16-bit unsigned value, written as'A'or'\u0041'.'A'is achar,"A"is aString.- Arithmetic on
chars works on their numeric codes;'7' - '0'is 7. - Escape sequences:
\n,\t,\",\',\\and more.\uescapes are processed before parsing, even in comments, so keep them inside literals only. - Unicode code points go up to U+10FFFF. BMP characters take one
char; supplementary characters (most emojis) take a surrogate pair of twochars; some visible symbols (flags, modified emojis) are several code points. String.length()countschars, not visible characters. Prefer whole strings and code-point methods over individualchars.booleanhas the valuestrueandfalse. Java never converts between numbers and booleans, which turnsif (x = 0)into a compile error.
Practice Questions
What do these print? System.out.println('a' + 1); System.out.println((char) ('a' + 1)); System.out.println("a" + 1);
98 (the code of 'a', 97, plus 1 gives an int), then b (the cast turns 98 back into a char), then a1 (string concatenation).
How do you print the text: He said "Use C:\temp"?
System.out.println("He said \"Use C:\\temp\"");. Escape each double quote as \" and the backslash as \\. Without the doubled backslash, \t would be a tab.
Why does the comment // file is in c:\users\data cause a compile error?
\u escapes are translated before the code is parsed, even inside comments. \users begins with \u, which must be followed by four hexadecimal digits. sers aren't hex digits, so the compiler reports an illegal Unicode escape.
The string "👍" (thumbs-up, U+1F44D) is stored in a Java String. What is its length(), and why?
2. U+1F44D is outside the Basic Multilingual Plane (above U+FFFF), so UTF-16 represents it with a surrogate pair: two char values. length() counts chars.
Can you write if (count) { ... } where count is an int, as in C?
No. Java conditions must be of type boolean, and there's no conversion from int to boolean. Write if (count != 0) { ... }.
How do you convert the character '9' into the int 9?
int n = c - '0'; (because the digit codes are consecutive), or Character.getNumericValue(c), or Character.digit(c, 10). Note that (int) '9' gives 57, the character code, not 9.
Previous: Java Primitive Types: Integers and Floating-Point Numbers Explained
Related reading
- Java Annotation Processors: Generating Source Code at Compile Time
- Processing Java Annotations at Runtime with Reflection
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
- Defining Custom Java Annotations: @interface, Elements, Retention and Target
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.