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

转载于:https://my.oschina.net/brucelee80/blog/161430

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值