How can we check whether an arithmetic operation will exceed the upper bounds of the data type before actually applying it.
Say upperbound for short in java is 32767 and I am multiplying 328*100, I can’t actually do comparison with Short.MAX_VALUE because after multiplication answer would already be overflown and answer would be -32736 which is certainly smaller than Short.MAX_VALUE
Take another example say I am int value of computing 17^10 (17 to the power 10) in a for loop. How do I know at what stage my answer got overflowed.
This Short and int thing is just an example. Think of this problem in bigger perceptive what exactly can be done for all data types.
I tried googling but found no good link which helps understand the concept.
There is a plan to include such methods in the Math package in Java 8, but I don’t know what the current status is. Some source code is available here. I don’t how tested the implementation is, but that could give you ideas.
For example, int multiplication is done by using longs:
But long multiplication uses a more complex algorithm: