Java has a value NaN. The value has multiple faces and is returned under different circumstances.
Below code samples will help us understand some of them.
public class JavaNaN
{
public static void main(String args[])
{
JavaNaN javaNaN = new JavaNaN();
javaNaN.proceed();
}
private void proceed()
{
double num = -5;
System.out.println("Math.sqrt returns NaN when used on a -ve number");
System.out.println("Math.sqrt(" + num + "): " + Math.sqrt(num));
System.out.println("\nThe output when casted to int yields zero (0)");
System.out.println("(int) Math.sqrt(" + num + "): " + (int) Math.sqrt(num));
System.out.println("\nThe output when casted to float yields NaN");
System.out.println("(float) Math.sqrt(" + num + "): " + (float) Math.sqrt(num));
}
}
/*
Expected output:
[root@mypc]# java JavaNaN
Math.sqrt returns NaN when used on a -ve number
Math.sqrt(-5.0): NaN
The output when casted to int yields zero (0)
(int) Math.sqrt(-5.0): 0
The output when casted to float yields NaN
(float) Math.sqrt(-5.0): NaN
*/
Visit the DevX Tip Bank