Description

On this document we will be showing a java example on how to use the intValue() method of BigInteger Class. Basically this method converts this BigInteger to a primitive int. 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 an int, only the low-order 32 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 byte range is from2147483647 to -2147483648 and these information is readily available through the Integer constants Integer.MIN_VALUE and Integer.MAX_VALUE.

Notes:

  • This method is specified by intValue in class Number.

Method Syntax

public int intValue()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

The intValue() method returns this BigInteger converted to primitive int.

Compatibility

Requires Java 1.1 and up

Java BigInteger intValue() Example

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

package com.javatutorialhq.java.examples;

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

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

public class BigIntegerIntValueExample {

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

		// get the int equivalent of each BigInteger
		int intVal1 = val1.intValue();
		int intVal2 = val2.intValue();
		
		// print the operation
		System.out.println("val1 in int is "+intVal1);
		System.out.println("val2 in int is "+intVal2);		
		
	}

}

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 int. We have printed out the result of conversion from BigInteger to int.

Sample Output

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

BigInteger intValue() example output