nerdexam
Oracle

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…

Working With Java Data Types

Question

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 is the result?

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)
  • A
    6% (1)
  • B
    11% (2)
  • C
    78% (14)
  • E
    6% (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 + s2 unboxes to short + int, which widens to int, and casting that result to long is 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 String is caught by the compiler, not at runtime. A ClassCastException only occurs at runtime when casting between reference types (e.g., Object to String), 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

#Auto-boxing/unboxing#Type casting#Type promotion#String conversion

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice