dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Using NaN in Java

Learn more about using NaN in Java, such as how it has multiple faces and is returned under different circumstances.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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

 





   
Srinath M. S. says: "I would love to leave a footprint in this flat world."
Thanks for your registration, follow us on our social networks to keep up-to-date