char, boolean and Unicode
Two primitives get a lesson of their own because both are easy to misread: a char looks like a character but is a 16-bit number, and a boolean looks like a number in other languages but is a type with exactly two values.
A char is a number
char holds one UTF-16 code unit, which is a number from 0 to 65535. A literal in single quotes is that number written as a character, and arithmetic on a char works on the number: adding one to 'A' gives 'B'.
The file Chars.java:
public class Chars {
public static void main(String[] args) {
char letter = 'A';
char next = (char) (letter + 1);
System.out.println("letter: " + letter);
System.out.println("next: " + next);
System.out.println("code: " + (int) letter);
String text = "Java";
System.out.println("first: " + text.charAt(0));
System.out.println("code: " + text.codePointAt(0));
System.out.println("digit: " + Character.isDigit('7'));
System.out.println("letter: " + Character.isLetter('7'));
System.out.println("upper: " + Character.toUpperCase('q'));
System.out.println("space: " + Character.isWhitespace(' '));
}
}
javac -Xlint:all Chars.java
java Chars
letter: A
next: B
code: 65
first: J
code: 74
digit: true
letter: false
upper: Q
space: true
The cast (char) is required because letter + 1 is an int: arithmetic widens the operands to at least int, and the result is narrowed back explicitly. A String stores its characters as a sequence of code units, which is why charAt takes an index.
Escapes
Some characters cannot be written directly in a literal, so a backslash starts an escape. The common ones are \n for a line feed, \t for a tab, \ for a backslash itself, ' for a single quote inside a character literal and \" for a double quote inside a string.
public class Escapes {
public static void main(String[] args) {
char newline = '\n';
char tab = '\t';
char quote = '\'';
char backslash = '\\';
System.out.println("codes: " + (int) newline + " " + (int) tab);
System.out.println("quote: " + quote);
System.out.println("backslash: " + backslash);
System.out.println("two\nlines");
}
}
javac -Xlint:all Escapes.java
java Escapes
codes: 10 9
quote: '
backslash: \
two
lines
The two codes are the Unicode values of the line feed and the tab, 10 and 9. The last call is one string with an escape in the middle, and println writes the line feed it contains, so the output is two lines.
The Character class
A primitive has no methods, so the JDK ships a wrapper class with static methods that take a char: Character.isDigit, isLetter, isWhitespace, toUpperCase, toLowerCase and the test isUpperCase. The last four lines of the first program of this lesson are those calls, and their output is the end of that program's run.
Character.isDigit('7') is true and Character.isLetter('7') is false, because a digit is not a letter even though both are characters. Character.toUpperCase('q') gives 'Q' and leaves its argument alone: the class is immutable, and every method returns a new value.
Code units and code points
UTF-16 writes most characters in one 16-bit unit and the rest in two. A char is one unit, so a character outside the basic plane takes two char values and one code point. The emoji below is such a character: length() is 2 and codePointCount is 1.
public class Emoji {
public static void main(String[] args) {
String emoji = "\uD83D\uDE00";
System.out.println("emoji: " + emoji);
System.out.println("length: " + emoji.length());
System.out.println("points: " + emoji.codePointCount(0, emoji.length()));
System.out.println("hex: " + Integer.toHexString(emoji.codePointAt(0)));
}
}
javac -Xlint:all Emoji.java
java Emoji
emoji: 😀
length: 2
points: 1
hex: 1f600
The two escapes \uD83D and \uDE00 are a surrogate pair, the UTF-16 encoding of the code point U+1F600. A loop over a string that counts code points must advance by Character.charCount(codePoint), not by one; a loop that counts code units can split a character in half.
boolean
boolean has two values, true and false, and no others. It is the type of every comparison and every logical operator, and the only type an if or a while accepts. ! negates it, && and || combine two of them.
public class Flags {
public static void main(String[] args) {
boolean ready = true;
boolean done = false;
System.out.println("ready: " + ready);
System.out.println("done: " + done);
System.out.println("not ready: " + !ready);
System.out.println("ready && done: " + (ready && done));
System.out.println("ready || done: " + (ready || done));
int count = 3;
boolean many = count > 2;
System.out.println("many: " + many);
String answer = many ? "yes" : "no";
System.out.println("answer: " + answer);
}
}
javac -Xlint:all Flags.java
java Flags
ready: true
done: false
not ready: false
ready && done: false
ready || done: true
many: true
answer: yes
The name of a boolean variable reads as a question, ready or isEmpty, and the condition reads as the answer. That is a convention, not a rule, but it makes a long if readable without a comment.
A boolean is not a number
In C a condition is an integer, and zero is false. Java has no such conversion: an int does not fit in a boolean and the compiler says so at the assignment, before any condition is read.
public class BooleanError {
public static void main(String[] args) {
boolean flag = 1;
System.out.println(flag);
}
}
javac -Xlint:all BooleanError.java
BooleanError.java:3: error: incompatible types: int cannot be converted to boolean
boolean flag = 1;
^
1 error
The comparison is the conversion: flag = count != 0 says what the C code meant. The rule also cuts the other way, so if (count) is an error for an int and if (flag == true) is legal but redundant, because flag is already the condition.
Exercises
- Print the characters from 'a' to 'f' with one loop and a cast.
- Write a string with a tab between two words and print it once. How many spaces does the terminal show?
- Count the code points of a string that holds one emoji and two letters. Compare length() with the count.
- Change boolean flag = 1; to boolean flag = count != 0; in BooleanError.java, declare count, and build it again.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many bits does a
charhave?Answer
16
A char is one UTF-16 code unit, and Character.SIZE is 16.
-
What does
(char) ('A' + 1)give?Answer
B
A is 65, the sum is 66, and the cast makes it the character B.
-
What does
Character.isLetter('7')return?Answer
false
A digit is not a letter; isDigit is the test that returns true for 7.
-
What does this program print?
public class Q1 { public static void main(String[] args) { String text = "a\nb"; System.out.println(text); } }Answer
a / b
The escape is a line feed inside the string, so println writes two lines.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(Character.toUpperCase('q')); } }Answer
Q
toUpperCase returns the upper-case character, and the argument is unchanged.
-
What does this program print?
public class Q3 { public static void main(String[] args) { boolean ready = 3 > 2; System.out.println(ready); } }Answer
true
The comparison is true, and a boolean prints as the word true.
-
What is the first line of the compiler output for this program?
public class Q4 { public static void main(String[] args) { boolean flag = 1; System.out.println(flag); } }Answer
error: incompatible types: int cannot be converted to boolean
Java does not convert a number to a boolean, so the assignment is refused.
-
What does this program print?
public class Q5 { public static void main(String[] args) { char c = 74; System.out.println(c); } }Answer
J
An int constant in the range of char may be assigned to it, and 74 is the letter J.
-
What does
!"".isEmpty()give for an empty string?Answer
false
An empty string is empty, so isEmpty is true and its negation is false.
-
How many
charvalues does one emoji outside the basic plane take?Answer
Two, a surrogate pair
Such a code point is encoded as a pair of UTF-16 code units, so length() counts two.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev