Java教程 - Java字符
在Java中,char存储字符。Java使用Unicode来表示字符。Unicode可以表示在所有人类语言中找到的所有字符。
Java char是16位类型。
字符的范围是 0
到 65,536
。没有负字符。
Char文字
Java中的字符是Unicode字符集的索引。字符表示在一对单引号内。例如,'a'
,'z'
和'@'
。
这里是一个程序,演示char变量:
public class Main { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2);//ch1 and ch2: X Y } }
上面的代码生成以下结果。

ch1
被分配值88,它是对应于字母 X
的ASCII(和Unicode)值。
例子
char
类型值可以用作整数类型和您可以执行算术运算。
public class Main { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1);//ch1 contains X ch1 = (char)(ch1 + 1); // increment ch1 System.out.println("ch1 is now " + ch1);//ch1 is now Y } }
上面的代码生成以下结果。

例2
下面的代码显示我们可以为非字母字符赋值Java字符类型。
public class Main { public static void main(String[] argv) { char ch = 'a'; System.out.println("ch is " + ch);//ch is a ch = '@'; System.out.println("ch is " + ch);//ch is @ ch = '#'; System.out.println("ch is " + ch);//ch is # ch = '$'; System.out.println("ch is " + ch);//ch is $ ch = '%'; System.out.println("ch is " + ch);//ch is % } }
上面的代码生成以下结果。

例3
以下代码将unicode值存储到char变量中。unicode文字使用 \\uxxxx
格式。
public class Main { public static void main(String[] args) { int x = 75; char y = (char) x; char half = "\\u00AB"; System.out.println("y is " + y + " and half is " + half); } }
上面的代码生成以下结果。

例4
转义序列用于输入不可能直接输入的字符。
转义字符值的语法:
'\''
用于单引号字符。'\n'
用于换行符。
对于八进制符号,请使用反斜杠,后跟三位数字。例如,'\141'
是字母'a'。
对于十六进制,您输入反斜杠-u( \u
),然后输入正好四个十六进制数字。例如,'\u0061'
"是ISO-Latin-1 'a'
,因为顶部字节为零。 '\ua432'
是日语片假名字符。
public class Main { public static void main(String[] argv) { char ch = '\''; System.out.println("ch is " + ch);//ch is ' } }
字符是一个简单的包装器。
上面的代码生成以下结果。

逃离值列表
下表显示了字符转义序列。
转义序列 | 描述 |
---|---|
\ddd | 八进制字符(ddd) |
\uxxxx | 十六进制Unicode字符(xxxx) |
\' | 单引号 |
\" | 双引号 |
\\ | 反斜杠 |
\r | 回车 |
\n | 换行 |
\f | 换页 |
\t | 转义字符 |
\b | 退格 |