1Z0-808 · Question #39
public static void main(String[] args) { Short s1 = 200; Integer s2 = 400; long s3 = (long) (s1 + s2); //line n1 String s4 = (String) (s3 * s2); //line n2 System.out.println("Sum is " + s4); } What…
The correct answer is C. Compilation fails at line n2. Casting a numeric primitive (long) to String is illegal in Java - there is no inheritance or conversion relationship between them, and the compiler detects this impossible cast at compile time on line n2, causing a compilation error. Why the distractors are wrong: A is wrong…
Question
Options
- ASum is 600
- BCompilation fails at line n1.
- CCompilation fails at line n2.
- DA ClassCastException is thrown at line n1.
- EA ClassCastException is thrown at line n2.
How the community answered
(18 responses)- A6% (1)
- B11% (2)
- C78% (14)
- E6% (1)
Explanation
Casting a numeric primitive (long) to String is illegal in Java - there is no inheritance or conversion relationship between them, and the compiler detects this impossible cast at compile time on line n2, causing a compilation error.
Why the distractors are wrong:
- A is wrong because the code never compiles, so no output is produced.
- B is wrong because line n1 is valid:
s1 + s2unboxes toshort + int, which widens toint, and casting that result tolongis a legal narrowing/widening primitive cast. - D is wrong because line n1 has no type incompatibility - the arithmetic and cast are entirely legal.
- E is wrong because the invalid cast to
Stringis caught by the compiler, not at runtime. AClassCastExceptiononly occurs at runtime when casting between reference types (e.g.,ObjecttoString), not when casting a primitive.
Memory tip: When you see a cast to String from a numeric type, alarm bells should ring - Java never allows casting numbers to String directly (use String.valueOf() or + "" instead), and the compiler will always catch it before the code runs.
Topics
Community Discussion
No community discussion yet for this question.