The Java char primitive type is a 16 bit representation of a single Unicode character.
The char type is based on the original Unicode specification, which used 16 bits to represent characters.
This is enough to cover most of the common letters and covers characters in the range 0x0000 to 0xFFFF.
The specification has since expanded the range of possible characters up to 0x01FFFF.
Multiple chars can comprise a string, such as "word", or chars can be processed independently.
A char literal is surrounded by single quotes (e.g. 'A').
char lowerA = 'a';
char upperB = 'B';
chars of a String
The String.toCharArray method returns a String's chars as an array.
As mentioned in arrays, you can use a for loop to iterate over the array.
String text = "Hello";
char[] asArray = text.toCharArray();
for (char ch: asArray) {
System.out.println(ch);
}
// Outputs:
// H
// e
// l
// l
// o
There are many builtin library methods to inspect and manipulate chars.
These can be found as static methods of the java.lang.Character class.
Here are some examples:
Character.isWhitespace(' '); // true
Character.isWhitespace('#'); // false
Character.isLetter('a'); // true
Character.isLetter('3'); // false
Character.isDigit('6'); // true
Character.isDigit('?'); // false
Some methods in the Character class have an overload so that it can take either an char or int.
For example, isDigit has one that accepts a char and another an int.
As mentioned earlier, the char type can only represent the characters in the range from 0x0000 to 0xFFFF.
The int, however, can represent all characters, hence the int overloads.
char to a String
The + operator can be used to add a char to a String.
'a' + " banana" // => "a banana"
"banana " + 'a' // => "banana a"
Becareful not to use + to join two chars together to form a String!
Adding two chars this way gives an int, not a String!
For example:
'b' + 'c';
// => 197 (not the String "bc")
This is because Java promotes the char to an int (see 4.2 Primitive Types and Values of the Java Language Specification).
However, when there are many characters to be added, it can be more efficient to use a StringBuilder instead:
StringBuilder builder = new StringBuilder();
builder.append('a');
builder.append('b');
builder.append('c');
String builtString = builder.toString();
// => abc