开发者

Does BigInteger ever overflows?

开发者 https://www.devze.com 2022-12-18 07:07 出处:网络
The API docs says All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the res开发者_StackOverflow社区ults of an operation.

The API docs says

All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the res开发者_StackOverflow社区ults of an operation.

Does this implies BigInteger will never overflow assuming you have sufficient memory available ? If so why do we let some "type" overflow and some don't ?

As the language evolves, will it favor the types which hide overflowing mechanism from the programmers ?


BigInteger will never overflow assuming you have enough memory to handle it.

To answer your question of why we let some types overflow and not others:

BigInteger is not really a type. It's a class. It's a wrapper class designed to give you the same functionality as an int, but allows you to use numbers as big as you need without the worry of overflow.

Types do overflow because they are simply a couple of bytes (exact amount depends on the type) of memory, and once that small amount of memory overflows, so do the numbers.

No class "overflows" unless it is specifically designed to do so (or if you run out of resources). A class is defined with enough memory for everything it contains, which would mostly be references to other classes or other data structures.


You read it right, it will never overflow. Although, it won't create more RAM for you :)

Semantics of arithmetic operations exactly mimic those of Java's integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the results of an operation.


BigInteger never overflows! It's of an arbitrary size, so it can accomodate a number as large as your memory (and Java heap) can accomodate.


Correct, BigInteger never overflows, it uses software operations and dynamic allocation to store arbitrarily sized numbers.

As with all things in computing, "arbitrarily sized" is anothe way of saying "until you run out of resources on the underlying system".


If so why do we let some "type" overflow and some don't?

That entirely depends on how it is backed. If it's backed by for example a plain vanilla primitive int, then it will obviously overflow at Integer.MAX_VALUE. Primitives have clear overflow borders, while those for Objects depends on how they're backed/programmed.

0

精彩评论

暂无评论...
验证码 换一张
取 消