Java convert BigInteger to short
Tags: BigInteger BigInteger shortValueExact BigInteger shortValue short
In this Java core tutorial we learn how to use the java.math.BigInteger.shortValueExact() and java.math.BigInteger.shortValue() method to convert a BigInteger object into a short value.
How to convert BigInteger object to short value
To convert a BigInteger value into a short value we can use the method java.math.BigInteger.shortValueExact(). This method also checks the value of BigInteger if it is out of range of short then an ArithmeticException is thrown.
ConvertBigIntegerToShortExample1.java
import java.math.BigInteger;
public class ConvertBigIntegerToShortExample1 {
public static void main(String... args) {
BigInteger value = new BigInteger("789");
short shortValue = value.shortValueExact();
System.out.println("BigInteger value: " + value);
System.out.println("short value: " + shortValue);
}
}
BigInteger value: 789
short value: 789
Using BigInteger.shortValue() method to get short value from BigInteger object
We also can use the java.math.BigInteger.shortValue() method which casts the BigInteger value to a short value.
ConvertBigIntegerToShortExample2.java
import java.math.BigInteger;
public class ConvertBigIntegerToShortExample2 {
public static void main(String... args) {
BigInteger value = new BigInteger("9999");
short shortValue = value.shortValue();
System.out.println("BigInteger value: " + value);
System.out.println("short value: " + shortValue);
}
}
BigInteger value: 9999
short value: 9999
Happy Coding 😊
Related Articles
Java convert BigInteger to String
Java convert BigInteger to long
Java convert BigInteger to int
Java convert BigInteger to float