Initializing java.math.BigInteger

Sorry cause this might look like a stupid yes or no question but I'm very new to this so I need an answer.

BigInteger i = BigInteger.valueOf(0);

and

BigInteger i = new BigInteger("0");

Are they the same?

Jon Skeet
people
quotationmark

They both end up with a reference to a BigInteger with a value of 0, but they're not identical in effect. In particular, as valueOf is a static method, it can make use of caching, and return the same reference if you call it twice:

BigInteger a = BigInteger.valueOf(0);
BigInteger b = BigInteger.valueOf(0);
System.out.println(a == b); // true on my machine

That doesn't appear to be guaranteed, but it's certainly somewhat expected given the documentation:

Returns a BigInteger whose value is equal to that of the specified long. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

When you call the constructor, you really will get a new instance every time.

That said, for this particular example, I'd just use BigInteger.ZERO...

people

See more on this question at Stackoverflow