Can I assign any value to n without it overflowing?
There are limits to what a BigInteger
can represent. As the javadoc says:
"
BigInteger
must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range."
Later on, it says:
"
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range ..."
... so you don't get unannounced overflows (like you do with primitive integer types) or INF/NaN-like values (like floating point types).
There is also the issue that if the heap is full / too small, creation of a large BigInteger
will throw an OOME.
If overflow is the problem ...
In your example, overflow in the BigInteger
code it is not the problem. You would be seeing exceptions of some kind.
Furthermore the expression 512*512*512
doesn't overflow. (But in general, you could get an overflow in the constructor argument expressions ... because those calculations are typically done using primitive integer arithmetic, which overflows silently.)
(Pedantically ... the assignment n = p;
is a reference assignment, and cannot overflow or throw an OOME. AFAIK, there is no way that it can fail within the context of the Java model. You'd need a hardware error, power failure, heap corruption, code generation bug, etc ...)