什么是字符文字中的转义数字的Java语义,例如。 '\15'? [英] What are the Java semantics of an escaped number in a character literal, e.g. '\15' ?
问题描述
请解释执行以下代码段时会发生什么:
Please explain what, exactly, happens when the following sections of code are executed:
int a='\15';
System.out.println(a);
这会列出13;
int a='\25';
System.out.println(a);
这会列出21;
int a='\100';
System.out.println(a);
这将打印出64个。
推荐答案
您分配了一个字符文字,由单引号分隔,例如'a'
(与String文字不同,用双引号分隔,例如a
)到 int
变量。 Java做了一个从16位无符号 char
到32位有符号 int
的自动扩展转换。
You have assigned a character literal, which is delimited by single quotes, eg 'a'
(as distinct from a String literal, which is delimited by double quotes, eg "a"
) to an int
variable. Java does an automatic widening cast from the 16-bit unsigned char
to the 32-bit signed int
.
但是,当字符文字是反斜杠后跟1-3位数字时,它是一个 八进制 ( base / radix 8)表示的字符。因此:
However, when a character literal is a backslash followed by 1-3 digits, it is an octal (base/radix 8) representation of the character. Thus:
-
\15
= 1×8 + 5 = 13回车;与'\r'
)相同 -
\25
= 2×8 + 5 = 21(NAK字符 - 否定确认) -
\100
= 1×64 + 0 ×8 + 0 = 64(@符号;与'@
)相同
\15
= 1×8 + 5 = 13 (a carriage return; same as'\r'
)\25
= 2×8 + 5 = 21 (a NAK char - negative acknowledgement)\100
= 1×64 + 0×8 + 0 = 64 (the @ symbol; same as'@'
)
有关字符文字和转义序列的详细信息,请参阅JLS章节:
For more info on character literals and escape sequences, see JLS sections:
- 3.10.4: Character Literals
- 3.10.6: Escape Sequences for Character and String Literals
引用 BNF from 3.10.6:
Quoting the BNF from 3.10.6:
OctalEscape:
\ OctalDigit
\ OctalDigit OctalDigit
\ ZeroToThree OctalDigit OctalDigit
OctalDigit: one of
0 1 2 3 4 5 6 7
ZeroToThree: one of
0 1 2 3
这篇关于什么是字符文字中的转义数字的Java语义,例如。 '\15'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!