java解惑之大问题

import java.util.*;
import java.math.BigInteger;
public class FiftySixth{
        public static void main(String[] args){
                BigInteger one = new BigInteger("500");
                BigInteger two = new BigInteger("5000");
                BigInteger three = new BigInteger("50000");
                BigInteger total = BigInteger.ZERO;
                total.add(one);
                total.add(two);
                total.add(three);
                System.out.println(total);
        }
}

输出多少?

0

怎么会呢?不是加了吗?

注意了BigInteger是不可变类型

不可变类型:

String,Integer,BigDecimal,Long,Charactor,Short,Byte,Boolean,Float,Double

再看看BigInteger的方法:

BigInteger add(BigInteger val)Returns a BigInteger whose value is (this + val)

BigInteger divide(BigInteger val)Returns a BigInteger whose value is (this / val).

int intValue()Converts this BigInteger to an int.

BigIntegernegate()Returns a BigInteger whose value is (-this)

BigIntegersubtract(BigInteger val)Returns a BigInteger whose value is (this - val).

可以观察到,加减乘除的返回值都是BigInteger,这也说明最终的运算是返回结果,但是不改变原值。

也可以这样理解

int i=0;

i+1+2+3+4+5+6;

那么i的值是多少?当然是0啦!!!

你可能感兴趣的:(BIgInteger,Java解惑)