Sudix
Sudix

Reputation: 360

Java - Check for Overflow by default

Of cause, checked overflow might slow down the code, and therefore not be an option in time critical sections.

In vast parts of the code however, the slight slowdown in execution speed seems irrelevant, and some other languages take care of avoiding overflow by themselves. While I am aware that since Java 8 there are methods in the Math library that allow for checked arithmetic operations, they are quite verbose and a hassle to use.

E.g.:

a + b
vs.
addExact(a,b)

Instead I am looking for a way (library/IDE?) that allows me to use + as checked addition and so on, and instead provide methods for unchecked arithmetic for the rare case one truly intends the behavior.

Upvotes: 1

Views: 174

Answers (2)

Stephen C
Stephen C

Reputation: 718788

Instead I am looking for a way (library/IDE?) that allows me to use + as checked addition and so on, and instead provide methods for unchecked arithmetic for the rare case one truly intends the behavior.

There is no Java IDE / library / Java language feature / whatever that does that.

The Java language doesn't check for underflow. The integral types use modular arithmetic. And you won't find any less verbose to do non-overflowing arithmetic than those methods in the Math class.

If you need to do lots of arithmetic with underflow or overflow checking AND you want the language to do something about it, take a look at what some other programming languages do; e.g. the Wikipedia article on Integer Overflow.

Upvotes: 0

Armin
Armin

Reputation: 168

Using a + for checked arithmetic would imply overloading the default operator behaviour, which Java doesn't allow (see Why doesn't java allow operator overloading). Therefore such functionality cannot be implemented.

That said your best bet for saving some typing would be to bind a text snippet to a + (so a + and space turn into addExact(a,).

Upvotes: 1

Related Questions