java.math.BigInteger shortValueExact()


On this document we will be showing a java example on how to use the shortValueExact() method of BigInteger Class. Basically this method converts this BigInteger to a primitive short and checking for lost information. The checking of lost of information is somewhat necessary because the BigInteger has a lot more precision than short so basically when we do narrowing, there are cases that we might lose some precision. If the case wherein there would be some lost of information or should we say that this BigInteger cannot exactly fit in a short, an ArithmeticException will be thrown.

For reference the int range is from -32768 to 32767  and these information is readily available through the Short constants Short.MIN_VALUE and Short.MAX_VALUE.

Method Syntax

public short shortValueExact()

Method Argument

Data Type Parameter Description

Method Returns

The shortValueExact() method returns this BigInteger converted to primitive short.


Requires Java 1.8 and up

Java BigInteger shortValueExact() Example

Below is a java code demonstrates the use of shortValueExact() method of BigInteger class. The example presented might be simple however it shows the behavior of the shortValueExact() method.


import java.math.BigInteger;
import java.util.Scanner;

 * A java example source code to demonstrate
 * the use of shortValueExact() method of BigInteger class

public class BigIntegerShortValueExactExample {

	public static void main(String[] args) {	
		// Declare and initialize our BigInteger values
		BigInteger val1 = new BigInteger("12");
		BigInteger val2 = new BigInteger("1509289");
		//BigInteger val2 = new BigInteger("143");		

		// get the int equivalent of each BigInteger
		int shortVal1 = val1.shortValueExact();
		int shortVal2 = val2.shortValueExact();
		// print the operation
		System.out.println("val1 in short is "+shortVal1);
		System.out.println("val2 in short is "+shortVal2);		


This example is a lot simpler than it looks. We only initialize two BigInteger which is within range of primitive type short. To further simulate the use of the shortValueExact, we have added a commented entry on which is outside the range of short. We have included an animated gif to show the behaviour of the commented entry.

Sample Output

Below is the sample output when you run the above example.

BigInteger shortValueExact() example output