Two Laptop Bag*
The moose likes Beginning Java and the fly likes int Addition/Subtraction Overflow Detection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "int Addition/Subtraction Overflow Detection" Watch "int Addition/Subtraction Overflow Detection" New topic
Author

int Addition/Subtraction Overflow Detection

Lambert Stein
Greenhorn

Joined: Oct 30, 2006
Posts: 14
How would you do this EFFICIENTLY?
By that I mean that, if it is done in a tight loop, it would execute fast. Simply checking against the same result done in long doesn't help - it's got the overhead of casting.
Thank!
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Lambert Stein]: Simply checking against the same result done in long doesn't help - it's got the overhead of casting.

I think this attitude is impractical - anything you do here will be slower than a single unchecked addition or subtraction. You can't reject a possibility because you think it's slower than you'd like - you can only choose the best option you can come up with, whatever its speed. Don't reject an option unless you have a better one in mind.

Having said that, you may get faster results like this:

I have not tested this at all, however. I will be interested to hear if you find something faster.
[ October 08, 2007: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

Of course that does not work, since the check will cause an overflow too, therefore the check will pass.


Output:
-2
1

And you're not going to tell me that there was no overflow here


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Ah, yes. I actually wrote a SafeMath class some years ago and worked through all these, testing carefully. But obviously I don't remember the results as well as I should. (And can't find the class on my computers; oh well.) That trick I used works well with multiplication and division, but not addition and subtraction. All, right, try this:

The condition can be written more compactly, but I've tried to arrange it for maximum efficiency.
[ October 08, 2007: Message edited by: Jim Yingst ]
Lambert Stein
Greenhorn

Joined: Oct 30, 2006
Posts: 14
So apparently it can't be done any other way than mine, right?
Sure, I guess the previous post will work, but I was trying to avoid 'if' statements.
Thanks to all, though!
 
jQuery in Action, 2nd edition
 
subject: int Addition/Subtraction Overflow Detection
 
Similar Threads
Posting from HTML form to java applet
Printng Event
Passing variables jsp and servlet
downloading generated report in JSF
starting service from java process