java.math.BigInteger longValue()
Description
On this document we will be showing a java example on how to use the longValue() method of BigInteger Class. Basically this method converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
For reference the long range is from -9223372036854775808 to 9223372036854775807 and these information is readily available through the Long constants Long.MIN_VALUE and Long.MAX_VALUE.
Notes:
- This method is specified by longValue in class Number.
Method Syntax
public long longValue()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The longValue() method returns this BigInteger converted to primitive long.
Compatibility
Requires Java 1.1 and up
Java BigInteger longValue() Example
Below is a java code demonstrates the use of longValue() method of BigInteger class. The example presented might be simple however it shows the behavior of the longValue() method.
package com.javatutorialhq.java.examples; import java.math.BigInteger; /* * A java example source code to demonstrate * the use of longValue() method of BigInteger class */ public class BigIntegerLongValueExample { public static void main(String[] args) { // Declare and initialize our BigInteger values BigInteger val1 = new BigInteger("12"); BigInteger val2 = new BigInteger("10223372036854775807"); // get the long equivalent of each BigInteger long longVal1 = val1.longValue(); long longVal2 = val2.longValue(); // print the operation System.out.println("val1 in int is "+longVal1); System.out.println("val2 in int is "+longVal2); } }
This example is a lot simpler than it looks. We only initialize two BigInteger, one is certainly within range and the other one is outside the range of long. We have printed out the result of conversion from BigInteger to long.