Open In App

BigInteger longValue() Method in Java

Last Updated : 07 Oct, 2022
Suggest changes
Share
Like Article
Like
Report

The java.math.BigInteger.longValue() converts this BigInteger to a long value. If the value return by this function is too big to fit into long value, then it will return only the low-order 64 bits. There is chance that this conversion can lose information about the overall magnitude of the BigInteger value. This method can also return the result with opposite sign. Syntax:

public long longValue()

Returns: The method returns a long value which represents long value for this BigInteger. Examples:

Input: BigInteger1=3214558191 Output: 3214558191 Explanation: BigInteger1.longValue()=3214558191. Input: BigInteger1=32145535361361525377 Output: -4747952786057577855 Explanation: BigInteger1.longValue()=-4747952786057577855. This BigInteger is too big for longValue so it is returning lower 64 bit.

Example 1: Below programs illustrate longValue() method of BigInteger class 

Java
// Java program to demonstrate longValue() method of BigInteger import java.math.BigInteger; public class GFG {  public static void main(String[] args)  {  // Creating 2 BigInteger objects  BigInteger b1, b2;  b1 = new BigInteger("3214553537");  b2 = new BigInteger("76137217351");  // apply longValue() method  long longValueOfb1 = b1.longValue();  long longValueOfb2 = b2.longValue();  // print longValue  System.out.println("longValue of "  + b1 + " : " + longValueOfb1);  System.out.println("longValue of "  + b2 + " : " + longValueOfb2);  } } 
Output:
longValue of 3214553537 : 3214553537 longValue of 76137217351 : 76137217351

Example 2: when return long is too big for long value. 

Java
// Java program to demonstrate longValue() method of BigInteger import java.math.BigInteger; public class GFG {  public static void main(String[] args)  {  // Creating 2 BigInteger objects  BigInteger b1, b2;  b1 = new BigInteger("32145535361361525377");  b2 = new BigInteger("7613721535372632367351");  // apply longValue() method  long longValueOfb1 = b1.longValue();  long longValueOfb2 = b2.longValue();  // print longValue  System.out.println("longValue of "  + b1 + " : " + longValueOfb1);  System.out.println("longValue of "  + b2 + " : " + longValueOfb2);  } } 
Output:
longValue of 32145535361361525377 : -4747952786057577855 longValue of 7613721535372632367351 : -4783767069412450057

Reference: BigInteger longValue() Docs


Similar Reads