What are the Java semantics of an escaped number in a character literal, e.g. '\15' ?

泄露秘密 提交于 2019-11-27 09:43:12

问题


Please explain what, exactly, happens when the following sections of code are executed:

int a='\15';
System.out.println(a);

this prints out 13;

int a='\25';
System.out.println(a);

this prints out 21;

int a='\100';
System.out.println(a);

this prints out 64.


回答1:


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.

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 (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 '@')

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

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



回答2:


The notation \nnn denotes an octal character code in Java. so int a = '\15' assigns the auto-cast'ed value of octal character 15 to a which is decimal 13.




回答3:


The fact that you put the digits in quotes makes me suspect it is interpreting the number as a character literal. The digits that follow must be in octal.



来源:https://stackoverflow.com/questions/19108008/what-are-the-java-semantics-of-an-escaped-number-in-a-character-literal-e-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!