Java casts and narrowing — which of the following lines are legal (compile successfully)?\n\n1) int w = (int)888.8;\n2) byte x = (byte)1000L;\n3) long y = (byte)100;\n4) byte z = (byte)100L;\n\nAssume standard Java primitive conversion rules.

Difficulty: Easy

Correct Answer: All statements are correct.

Explanation:


Introduction / Context:
Java allows explicit narrowing primitive conversions even when information will be lost. This question asks which given assignments compile; the focus is legality (compilation), not value correctness at runtime.



Given Data / Assumptions:

  • All lines use explicit casts where narrowing is required.
  • Values may overflow the target type; compilation only requires a proper cast.


Concept / Approach:
Narrowing conversions (e.g., double → int, long → byte) require an explicit cast. Widening conversions (e.g., byte → long) are automatic. When an explicit cast is provided, the compiler accepts the conversion, even if the resulting value wraps or truncates.



Step-by-Step Solution:

1) (int)888.8 → legal; truncates to 888.2) (byte)1000L → legal; narrows long to byte, value wraps modulo 256.3) long y = (byte)100 → legal; byte 100 is then widened to long 100.4) (byte)100L → legal; long to byte with explicit cast.


Verification / Alternative check:
Remove the casts in lines 2 and 4 and compilation fails (possible lossy conversion). Keeping casts ensures success.



Why Other Options Are Wrong:

  • Options selecting subsets ignore that all four lines compile under Java’s casting rules.


Common Pitfalls:
Assuming the compiler rejects narrowing even with a cast; in fact it compiles but may change the runtime value.



Final Answer:
All statements are correct.

Discussion & Comments

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