在这篇博文中,我们将以java中的一个例子来学习BigInteger教程。你也可以查看我之前关于java中BigInteger类的文章。
BigInteger类介绍
BigInteger是JDK1.6中引入的java.math包中的一个java对象。
Integer Primitive存储的数值范围为2的31次方-1-2的31次方。Long Primitive存储的数值范围为2的63次方-1-2的63次方。
int value=1231212312312312312312312;
Java编译器抛出这个错误,因为该值超出了整数的范围。为了处理这些数值,Java引入了大整数类。当我们对整数或长数进行运算时,如果运算结果不符合它们的范围,对整数来说会保存低阶32位,对长数来说会保存64位,并给出低范围的结果。但是如果我们使用BigInteger,它就会给出正确的结果。
这可以用来存储无法存储在普通原始类型中的大数值的结果。BigInteger也可用于许多位操作和其他数学函数,可以存储超过2次方64的数值。
声明和初始化
BigInteger bigValue1,bigValue2;
bigValue1=new BigInteger(123);
bigValue2=BigInteger.valueOf(121);
or
BigInteger bi= new BigInteger("578");
它是一个不可变的类,当进行算术运算时,它不能改变现有的数值,而是用修改后的数值创建一个新的对象。
java中的大整数例子
import java.math.BigInteger;
public class BigIntegerDemo {
public static void main(String args[]) {
int integerMaximumValue = 2147483647;// This is maximum value for
// integer type i.e 2 power 31
System.out.println("Case=1 = " + integerMaximumValue);
System.out.println("Case=2 = " + (integerMaximumValue + 1));
System.out.println("Case=3 = " + (integerMaximumValue * 2));
System.out.println("Case=4 = " + (integerMaximumValue * 4));
// All the above cases expect Case=1 gives wrong value as overflow
// occured
// All the below cases gives expected values as BigInteger Object
// accomdates more values
BigInteger bigIntegerdemo = BigInteger.valueOf(integerMaximumValue);
System.out.println();
System.out.println("Case=5 " + bigIntegerdemo);
System.out.println("Case=6 " + bigIntegerdemo.add(BigInteger.ONE));
System.out.println("Case=7 "
+ bigIntegerdemo.multiply(BigInteger.valueOf(3)));
System.out.println("Case=8 "
+ bigIntegerdemo.multiply(BigInteger.valueOf(4)));
}
}
输出:
Case=1 = 2147483647
Case=2 = -2147483648
Case=3 = -2
Case=4 = -4
Case=5 2147483647
Case=6 2147483648
Case=7 6442450941
Case=8 8589934588
附上BigInteger中可用的方法,并使用javap命令。

这个主题是探索BigInteger例子的一个非常基本的开始。希望你有足够的信息可以开始学习。如果你有任何问题,请随时留言,我会给你答复。