Write a program that extracts the primitive type value from the given BigInteger.
Java program to convert BigInteger to a primitive type
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger nr = BigInteger.valueOf(Long.MAX_VALUE);
long nrLong = nr.longValue();
System.out.println(nr + " as long is: " + nrLong);
int nrInt = nr.intValue();
System.out.println(nr + " as int is: " + nrInt);
short nrShort = nr.shortValue();
System.out.println(nr + " as short is: " + nrShort);
byte nrByte = nr.byteValue();
System.out.println(nr + " as byte is: " + nrByte);
long nrExactLong = nr.longValueExact(); // ok
System.out.println(nr + " as exact long is: " + nrExactLong);
}
}
Output:
9223372036854775807 as long is: 9223372036854775807
9223372036854775807 as int is: -1
9223372036854775807 as short is: -1
9223372036854775807 as byte is: -1
9223372036854775807 as exact long is: 9223372036854775807
Comments
Post a Comment