In Java (IEEE 754 math), what does the following print? System.out.println(Math.sqrt(-4D));

Difficulty: Easy

Correct Answer: NaN

Explanation:


Introduction / Context:
Java’s Math library follows IEEE 754 floating-point rules. The square root of a negative real number is not defined in the reals, so Math.sqrt returns the special floating-point value NaN (Not-a-Number) rather than throwing an exception.


Given Data / Assumptions:

  • Argument is -4D, a double literal.
  • We are using Math.sqrt(double).


Concept / Approach:
For negative inputs, many Math functions are defined to return NaN. Java does not use exceptions for these domain errors in the Math class; instead, it propagates NaN, which prints as the string "NaN".


Step-by-Step Solution:

Compute sqrt(-4D) under IEEE 754 → NaN System.out prints "NaN"


Verification / Alternative check:
Double.isNaN(Math.sqrt(-4)) returns true. To compute square roots of negative numbers as complex values, use a complex number library instead of Math.sqrt.


Why Other Options Are Wrong:

  • -2: would be the real square root of +4, not -4.
  • Compile Error / Runtime Exception: not thrown for this method.
  • Infinity: returned by operations like division by zero for nonzero numerators, not here.


Common Pitfalls:
Expecting exceptions from Math for domain errors; in Java, NaN is the standard signal value.


Final Answer:
NaN

More Questions from Java.lang Class

Discussion & Comments

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