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("
The output when casted to int yields zero (0)");System.out.println("(int) Math.sqrt(" + num + "): " + (int) Math.sqrt(num));System.out.println("
The output when casted to float yields NaN");System.out.println("(float) Math.sqrt(" + num + "): " + (float) Math.sqrt(num));}}/*

Expected output:

[[email protected]]# java JavaNaNMath.sqrt returns NaN when used on a -ve numberMath.sqrt(-5.0): NaNThe output when casted to int yields zero (0)(int) Math.sqrt(-5.0): 0The output when casted to float yields NaN(float) Math.sqrt(-5.0): NaN*/
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts