Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

syntax - 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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ' ')
  • 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...