In Java, which three of the following are valid char declarations or assignments?

Difficulty: Medium

Correct Answer: 1, 3, 6

Explanation:


Introduction / Context:
Java char is a 16-bit unsigned UTF-16 code unit. It can be initialized by a single-quoted character, a Unicode escape within single quotes, or an integral literal within range 0..65535.



Given Data / Assumptions:

  • c1 = 064770; c2 = 'face'; c3 = 0xbeef; c4 = \u0022; c5 = '\iface'; c6 = '\uface'
  • Octal/hex integer literals are allowed if in range; Unicode escapes must be within single quotes to form a char literal.


Concept / Approach:
Legal forms: char c = 'A'; char c = '\u0041'; char c = 65; Illegal forms include multi-character literals and missing quotes around Unicode escapes.



Step-by-Step Solution:

c1 = 064770; → octal int literal 0o64770 equals 27128 (within 0..65535) → valid.c2 = 'face' → multiple characters; Java char must be one code unit → invalid.c3 = 0xbeef → hex int 48879 fits char range → valid.c4 = \u0022 → missing quotes; should be '\u0022' → invalid as written.c5 = '\iface' → illegal escape \i and too many chars → invalid.c6 = '\uface' → Unicode escape with four hex digits FACE (64206) in single quotes → valid.


Verification / Alternative check:
Compile each line independently; only 1, 3, and 6 succeed without additional casts.



Why Other Options Are Wrong:
They include invalid forms (multi-char literal, missing quotes, or illegal escape).



Common Pitfalls:
Forgetting quotes around Unicode escapes; misusing escapes; assuming char can hold strings.



Final Answer:
1, 3, 6

More Questions from Language Fundamentals

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion