NaN, Infinity - 1

"Hi, Amigo!"

"Today I'm going to tell you about some interesting things in Java."

"Infinity."

In Java, the double type has special values for positive infinity and negative infinity. A positive number divided by 0.0 yields positive infinity, and a negative number — negative infinity.

These concepts are represented by special Double constants:

Code Description
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
Positive infinity
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
Negative infinity

"And that really works?"

"Yes. Look at this:"

Code
double inf = Double.POSITIVE_INFINITY;
System.out.println(inf); // Infinity
System.out.println(inf + 1); // Infinity+1 == Infinity
System.out.println(inf + 10); // Infinity+10 == Infinity
System.out.println(inf * -1); // Equal to negative infinity
Double.NEGATIVE_INFINITY
Screen output:
Infinity
Infinity
Infinity
-Infinity

"It really works. And if we have ambiguity? For example, if we subtract infinity from infinity?"

"For this, Java has another concept: Not-a-Number (NaN)."

"It's used in various situations:"

1) The string is being converted to a number, but it contains letters. The result is NaN.

2) Infinity minus infinity. The result is NaN.

3) Many other situations where we expect a number, but we end up with something undefined.

"So, what operations can you perform with Infinity and NaN?"

"With NaN, it's very simple. Any operation involving NaN results in NaN."

"And with infinity, you can do the following:"

Expression Result
n ÷ ±Infinity
0
±Infinity × ±Infinity
±Infinity
±(something other than zero) ÷ 0
±Infinity
Infinity + Infinity
Infinity
±0 ÷ ±0
NaN
Infinity - Infinity
NaN
±Infinity ÷ ±Infinity
NaN
±Infinity × 0
NaN

"That makes sense. Thank you, Rishi."