In Java (parsing and rounding), what does this code print? public class NFE { public static void main(String [] args) { String s = "42"; try { s = s.concat(".5"); /* Line 8 */ double d = Double.parseDouble(s); s = Double.toString(d); int x = (int) Math.ceil(Double.valueOf(s).doubleValue()); System.out.println(x); } catch (NumberFormatException e) { System.out.println("bad number"); } } }

Difficulty: Easy

Correct Answer: 43

Explanation:


Introduction / Context:
This snippet chains parsing, formatting, and rounding. The key is understanding that Math.ceil rounds up to the nearest integer (as a double) and that casting to int then truncates toward zero, preserving the rounded integer value in this case.


Given Data / Assumptions:

  • Start s = "42", then s.concat(".5") → "42.5".
  • Double.parseDouble("42.5") succeeds, producing 42.5.
  • Math.ceil(42.5) = 43.0.
  • Cast 43.0 to int → 43.


Concept / Approach:
Double.valueOf(s).doubleValue() is redundant after parsing, but it returns the same double. Math.ceil returns a double whose value is the smallest integer greater than or equal to the argument. Casting this value to int simply yields that integer.


Step-by-Step Solution:

s = "42" → s = "42.5" d = 42.5 ceil(42.5) = 43.0 (int)43.0 = 43 Print 43


Verification / Alternative check:
Had the code used Math.floor, the result would be 42. Using Math.round(42.5) would yield 43 as well (ties go to +∞ for positive halves in Java’s round-to-nearest-even? Actually, round(42.5) = 43 in Java).


Why Other Options Are Wrong:

  • 42 or 42.5: ignore the effect of ceil and integer casting.
  • "bad number": parsing "42.5" is valid for Double.


Common Pitfalls:
Expecting a NumberFormatException from "42.5"; that would occur for Integer.parseInt, not Double.parseDouble.


Final Answer:
43

Discussion & Comments

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