在Java中,有CPU原生提供的整型最大范围64位long型整型。
使用long型整数可以直接通过CPU指令进行计算,速度非常快。
如果我们使用的整数范围超过了long怎么办了?
java.math.BigInteger就是用来表示任意大小的整数。
BigInteger内部用一个int[]数组来模拟一个非常大的整数。
BigInteger bi = new BigInteger("12334567890");
System.out.println(bi.pow(5)); //285508931350653308728472814534367643427048294900000
对BigInteger做运算的时候,只能使用实例方法,例如:加法运算;
public classcatchExample2 {public static voidmain(String[] args) {
BigInteger b1= new BigInteger("12334567890");
BigInteger b2= new BigInteger("123123131");
BigInteger sum=b1.add(b2);
System.out.println(sum);//12457691021
}
}
和long型整数运算比,BigInteger不会有范围限制,但缺点是速度比较慢。
也可以把BigInteger转换成long型:
public classcatchExample2 {public static voidmain(String[] args) {
BigInteger b1= new BigInteger("12334567890");
System.out.println(b1.longValue());
System.out.println(b1.multiply(b1).longValueExact());//java.lang.ArithmeticException: BigInteger out of long range
}
}
在使用longValueExact()方法时,如果超出了long型的范围,会抛出ArithmeticException。
BigInteger和Integer、long一样,也是不可变类,并且也继承自Number类,
因为Number定义了转换为基本类型的几个方法:
• 转换为byte:byteValue()
• 转换为short:shortValue()
• 转换为int:intValue()
• 转换为long:longValue()
• 转换为float:floatValue()
• 转换为double:doubleValue()
因此,通过上述方法,可以把BigInteger转换成基本类型。
如果BigInteger表示的范围超过了基本类型的范围,转换时将丢失高位信息,即结果不一定是准确的。
如果需要准确的转换成基本类型,可以使用inValueExact()、longValueExact()等方法。
在转换时如果超出范围,将直接抛出ArithmeticExecption异常。