devxlogo

Using NaN in Java

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:

[root@mypc]# 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*/
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist