char 原语

char 可以存储单个 16 位 Unicode 字符。字符文字用单引号括起来

char myChar = 'u';
char myChar2 = '5';
char myChar3 = 65; // myChar3 == 'A'

它的最小值为\u0000(十进制表示中的 0,也称为空字符 ),最大值为\uffff(65,535)。

char 的默认值是\u0000

char defaultChar;    // defaultChar == \u0000

为了定义'值的 char,必须使用转义序列(前面带有反斜杠的字符):

char singleQuote = '\'';

还有其他转义序列:

char tab = '\t';
char backspace = '\b';
char newline = '\n';
char carriageReturn = '\r';
char formfeed = '\f';
char singleQuote = '\'';
char doubleQuote = '\"'; // escaping redundant here; '"' would be the same; however still allowed
char backslash = '\\';
char unicodeChar = '\uXXXX' // XXXX represents the Unicode-value of the character you want to display

你可以声明任何 Unicode 字符的 char

char heart = '\u2764';
System.out.println(Character.toString(heart)); // Prints a line containing "❤".

也可以添加到 char。例如,要遍历每个小写字母,你可以执行以下操作:

for (int i = 0; i <= 26; i++) {
    char letter = (char) ('a' + i);
    System.out.println(letter);
}