Java Math.sqrt with a negative argument: what will this program print? public class SqrtExample { public static void main(String [] args) { double value = -9.0; System.out.println(Math.sqrt(value)); } }

Difficulty: Easy

Correct Answer: NaN

Explanation:

Introduction / Context: This checks knowledge of Java’s floating-point math rules. The square root of a negative real is not a real number; in Java’s Double semantics, Math.sqrt of a negative argument returns the special value NaN (Not-a-Number).

Given Data / Assumptions:

  • value = -9.0 (a negative double).
  • Method used: Math.sqrt(double).
  • Printed output is whatever Math.sqrt returns.

Concept / Approach: IEEE 754 floating-point rules apply. For domain errors like sqrt of a negative real, Java returns NaN instead of throwing a checked exception. Printing a NaN double shows the literal text "NaN".

Step-by-Step Solution: Compute Math.sqrt(-9.0) → NaN. System.out.println prints NaN as a token.

Verification / Alternative check: If you first cast to a complex type or use libraries supporting complex numbers, you could represent 3i; but standard Math.sqrt returns NaN for negatives.

Why Other Options Are Wrong: 3.0/-3.0 are real roots and do not apply; compilation succeeds; no ArithmeticException is thrown by Math.sqrt for negative doubles.

Common Pitfalls: Assuming integer/real math throws exceptions in Java like division by zero scenarios; confusing NaN with Infinity.

Final Answer: NaN

More Questions from Java.lang Class

Discussion & Comments

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