In Java, characters are represented by the primitive data type char. A char can hold a single Unicode character, which includes ASCII characters, as well as characters from many other writing systems.
Here are some important facts about char in Java:
- A
charis a 16-bit unsigned integer that can represent any character in the Unicode standard. - You can assign a
chara value using a single character enclosed in single quotes, like this:char myChar = 'a'; - You can also assign a
chara value using its Unicode code point, like this:char myChar = '\u0061';(which is the Unicode code point for the character ‘a’). - There are several special escape sequences that can be used to represent characters that cannot be easily typed, such as newline (
\n), tab (\t), and Unicode characters represented by their hex value, such as\u00E9for the character é. charvalues can be compared using standard relational operators (<,<=,>,>=), which compare the Unicode code points of the characters.
Here’s an example that demonstrates some of these concepts:
char myChar = 'a';
char newline = '\n';
char accentedE = '\u00E9';
System.out.println(myChar);
System.out.println(newline);
System.out.println(accentedE);
System.out.println('a' < 'b'); // prints "true"
System.out.println('A' < 'a'); // prints "true"
This code declares a char variable called myChar and assigns it the value 'a'. It also declares two more char variables, newline and accentedE, and assigns them values using special escape sequences and a Unicode code point, respectively. The code then prints out these characters and some comparisons of char values using the < operator.
