Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I express NaN for integer types in Java?

Tags:

I have a method returning long and there are cases where a valid result can not be computed. Double has the NaN constant, which is not expressable in long.

I can think of two solutions:

  • throw an exception
  • change the method's signature to return double, check for NaN and convert to long if everything is fine.

Is either preferrable / more "Javanic"? Are there other ways / Did I miss something obvious?

like image 891
Hanno Fietz Avatar asked Nov 30 '11 16:11

Hanno Fietz


People also ask

Can NaN be an integer?

No, NaN is a floating point value. Every possible value of an int is a number.

How NaN is represented Java?

“NaN” stands for “not a number”. “Nan” is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined.

How does Java handle NaN value?

In mathematics, taking the square root of a negative number results in an imaginary number. This case is dealt with by returning NaN in Java. Taking mod of a number with zero, will return the remainder after dividing a value by zero. Hence, NaN is returned.

Is NaN function in Java?

isNaN() method in Float Class is a built in method in Java returns true if this Float value or the specified float value is Not-a-Number (NaN), or false otherwise. Parameters: he function accepts a single parameter val which specifies the value to be checked when called directly with the Float class as static method.


1 Answers

You can make the return-type Long (the boxed version of long) and return null.

like image 158
Björn Pollex Avatar answered Oct 13 '22 22:10

Björn Pollex