Home » Tip Bank » Java
  • Comment on this Article
Dec 10, 2018
  • facebook
  • twitter
  • google+
  • in
  • Email

WEBINAR:

On-Demand

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


Watch

Using NaN in Java

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
*/
Srinath MS
 
Submit a Tip
Browse "Java" Tips
Browse All Tips
html.net
activatejavascript.org