How to represent infinity in Java?
How to represent infinity in Java?
This article is part of a tutorial.
Tutorial Index page - Java Datatype representation
Introduction
"Infinity (symbolically represented with ∞) comes from the Latin infinitas or "unboundedness." It refers to several distinct concepts – usually linked to the idea of "without end" – which arise in philosophy, mathematics, and theology.
In mathematics, "infinity" is often used in contexts where it is treated as if it were a number (i.e., it counts or measures things: "an infinite number of terms")" http://en.wikipedia.org/wiki/Infinity
How is infinity represented in Java?
In Java, the wrapper classes (Double and Float) that wrap the value of the primary types double and float each in an object contain static constants holding the value of infinity of its respective type.
There are two of types infinities:
- Negative Infinity (In mathematics, symbolically represented by -∞)
- Positive Infinity (In mathematics, symbolically represented by ∞)
Number Classes
Class Double and Float extend the class Number- "The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short." see Java Docs
Double - Negative and Positive Infinities
- Double.NEGATIVE_INFINITY
A constant holding the negative infinity of type double.
- Double.POSITIVE_INFINITY
A constant holding the positive infinity of type double.
Float - Negative and Positive Infinities
- Float.NEGATIVE_INFINITY
A constant holding the negative infinity of type float .
- Float.POSITIVE_INFINITY
A constant holding the positive infinity of type float.
Examples
Consider some simple examples below
Using Negative Infinity:
In this example, the input is a number and and the number's validity should be checked by the given condition:
Condition for Validity: (-∞ <= x <= 20)
public boolean checkNumber(double number) { if( number >= Double.NEGATIVE_INFINITY &amp;&amp; number <= 20 ) { return true; } }
Using Positive Infinity:
In this example, the length of a String should only belong to only the specified range. The given range/restriction for the String is (1 <= x <= ∞)
public boolean checkLength(String value) { int length = value.length(); if( length >= 1 && length <= Double.POSITIVE_INFINITY ) { return true; } }
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
