NaN

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Inspect the documentation. What is the type of the argument expected by sqrt()?

double

What is the type of value returned by sqrt()?

double

Is sqrt() a static method?

Yes

NaN

If you look further at the documentation for sqrt() you find some details:

Returns the correctly rounded positive square root of a double value. If the argument is NaN or less than zero, the result is NaN.

NaN stands for "Not a Number". This is a 64-bit pattern that is returned by sqrt() when its argument is not correct. Here is an example run of the program:

C:/chap11>java SquareRoot
Enter a double: -3
square root   : NaN

Here the method returned the 64-bit pattern NaN. The println() method writes the characters "NaN" when it sees this pattern. (The actual bit pattern is not character data.)

In a highly secure, industrial-strength programming language like Java, the behavior of a function must be described for all possible input, both in range and out of range. The documentation describes all of these cases.

QUESTION 14:

What do you expect is the output of the following program fragment:

int x = 9;
System.out.println( Math.sqrt( x ) );