哪些声明有效?

Which declarations are valid?

Select三个正确答案(有效声明)。

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

\u0061 表示 a。您可以使用 \u0061 而不是 a,因此:

char \u0061 = 'a';

相同
char a = 'a';

ch\u0061r a = 'a';

相同
char a = 'a';

编译器可以识别 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) returns true.

A "Java letter-or-digit" is a character for which the method Character.isJavaIdentifierPart(int) returns true.

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.