6. Java转义字符

转载自:http://my.oschina.net/brucelee80/blog

Java转义字符

转义字符可以赋给字符型char及字符序列类String。
之所以会出现转义字符,是因为有些字符我们无法直接表示,比如换行符,回车符等,
又比如本身就是Java语言直接量分隔符的单引号'、双引号"等,所以下面的语句编译器都是无法识别的;
于是,这些符号需要转义来表示:

char c = ’\’’;  
Stirng s = “\””;

以转义前导符反斜杠“\”开头的字符,将转义成新的字符,而不再是它原本的字符。
转义字符有如下取值:

转义字符

描述

\t

横向跳格(\u0009)

\b

退格(\u0008)

\n

换行(\u000a)

\r

回车(\u000d)

\f

换页(\u000c)

\'

单引号(\u0027)

\"

双引号(\u0022)

\\

反斜杠(\u005c)

\ddd

\+三个八进制数

(最大是\377)

\udddd

\u+四个十六进制数

(最大是\uffff)

有趣的\u000a(或\u000d)

int x=1;
// \u000a x=2;
System.out.println(x); // 打印2而不是1
打印2而不是1,原因是\u000a或\u000d表换行,代码其实变成了如下, x=2还是执行了的
int x=1;
// 
int x=2;
System.out.println(x); // 打印2而不是1
所以 char c = ‘\u000a’;是不允许的,它会被看做两行
char c =’
‘;

注意写法

  1. 转义字符\U000f是错误的,U应该小写,它的表示范围是\u0000 ~ \uffff(或\uFFFF),后面四位十六进制数的大小写不区分。
  2. 转义字符\777是错误的,\+三位八进制数的转义,它的表示范围是\000 ~ \377,原因:
    http://stackoverflow.com/questions/9543026/why-do-java-octal-escapes-only-go-up-to-255
    Answer:
    It is probably for purely historical reasons that Java supports octal escape sequences at all. These escape sequences originated in C (or maybe in C's predecessors B and BCPL), in the days when computers like the PDP-7 ruled the Earth, and much programming was done in assembly or directly in machine code, and octal was the preferred number base for writing instruction codes, and there was no Unicode, just ASCII, so three octal digits were sufficient to represent the entire character set.

    By the time Unicode and Java came along, octal had pretty much given way to hexadecimal as the preferred number base when decimal just wouldn't do. So Java has its \u escape sequence that takes hexadecimal digits. The octal escape sequence was probably supported just to make C programmers comfortable, and to make it easy to copy'n'paste string constants from C programs into Java programs.

    Check out these links for historical trivia:
    http://en.wikipedia.org/wiki/Octal#In_computers
    http://en.wikipedia.org/wiki/PDP-11_architecture#Memory_management
转载自:http://my.oschina.net/brucelee80/blog

你可能感兴趣的:(\u000a,Java转义字符,\u000d,\777)