选择三个正确答案(有效声明)。
(a) char a = '\u0061';
(b) char 'a' = 'a';
(c) char\u0061 = 'a';
(d) ch\u0061r a = 'a';
(e) ch'a'r a = 'a';
答案:(a)、(c)和(d)
书:
A Programmer's Guide to Java SCJP Certification (Third Edition)
谁能解释一下选项 (c) 和 (d) 的原因,因为 IDE (IntelliJ IDEA) 以红色显示:
Cannot resolve symbol 'u0063'
最佳答案
编译器可以识别 Unicode 转义并将它们转换为 UTF-16。 ch\u0061r
将变为 char
,这是一个有效的原始类型。故选项 D 正确。
3.3. Unicode Escapes
A compiler for the Java programming language ("Java compiler") first recognizes Unicode escapes in its input, translating the ASCII characters \u followed by four hexadecimal digits to the UTF-16 code unit (§3.1) for the indicated hexadecimal value, and passing all other characters unchanged.
\u0061
将被翻译为 a
,这是一个有效的 Java 字母,可用于形成标识符。故 C 选项正确。
3.8. Identifiers
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
Identifier: IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral IdentifierChars: JavaLetter {JavaLetterOrDigit} JavaLetter: any Unicode character that is a "Java letter" JavaLetterOrDigit: any Unicode character that is a "Java letter-or-digit"
A "Java letter" is a character for which the method
Character.isJavaIdentifierStart(int)
returnstrue
.A "Java letter-or-digit" is a character for which the method
Character.isJavaIdentifierPart(int)
returnstrue
.The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (
\u0041-\u005a
), and a-z (\u0061-\u007a
), and, for historical reasons, the ASCII dollar sign ($
, or\u0024
) and underscore (_
, or\u005f
). The dollar sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems. The underscore may be used in identifiers formed of two or more characters, but it cannot be used as a one-character identifier due to being a keyword.
关于java - 哪些声明有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283074/