| Author |
integer overflow
|
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
Hello, Considering that Java does not automatically throw an exception (or otherwise object) to integer overflow (it just "wraps around"), what is the best/preferred/whatever style to handle this condition when it is unknown that the inputs and subsequent calculations will for certain stay within bounds (of Integer.MAX_VALUE and Integer.MIN_VALUE in the case of type int)? Should values first be stored as type long and the appropriate comparisons made before continuing? Then, in the case of using data of type long, is there a better way of handling the situation than first storing the data as BigInteger objects and making the appropriate comparisons? For the purposes of reuse, my thought was to create my own class with static methods that checked the input data and subsequent calculations that the appropriate bounds were not exceeded; but if they were, then trow some custom exception. Or is this function already in one of the standard Java classes? Thanks for the advice.
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
|
|
From the JLS, §4.2.2 Integer Operations:
The built-in integer operators do not indicate overflow or underflow in any way.
From that, I'm left with only trickery to determine when overflow or underflow occured. If your using an int, you can try an approach like this: This will vaguely work. However, if the overflow were so great that the ensuing wrapping brought the resultant value within the valid range of an int again, the overflow or underflow wouldn't be caught. Of course, this doesn't slove anything for catching overflow or underflow on a long... Sorry, this is the best way I know. Corey
|
SCJP Tipline, etc.
|
 |
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
Well, I searched all over the web for articles on this subject, and it would seem that no magic trick is available to deal with a possible integer overflow. Oh well. It looks as if we'll just have to do it the hard way. Nuts to that. Good Luck. [ April 05, 2002: Message edited by: Dirk Schreckmann ]
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
Here's what I came up with that might be useful for dealing with longs: Naturally you can add additional methods for subtraction and division, as well as any other operations you want to use. And it may well be possible to improve on the implementations I've provided - I just tossed them off quickly. But I think the basic idea is useful. If you do decide to build something like this, please let us know what you come up with - it may well be useful for others.
|
"I'm not back." - Bill Harding, Twister
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
|
Ahhh... here you go.
|
 |
 |
|
|
subject: integer overflow
|
|
|