herpderp
herpderp

Reputation: 16177

Java subtract two ints, result should be a minimum of zero

I want to subtract one integer from another, and the result should floor at 0. So 2 minus 4 should equal 0. I could just do

int result = x - y;
if (result < 0) result = 0;

But is there a more elegant way?

Upvotes: 2

Views: 22396

Answers (3)

Thomas Eding
Thomas Eding

Reputation: 1

int result = Math.max(0, x - y);

Upvotes: 26

Edwin Buck
Edwin Buck

Reputation: 70909

While a lot of people are rushing out with Math.max(...) solutions, I'd like to offer a simple if statement.

if (y > x) {
  result = 0;
} else {
  result = x - y;
}

It is guaranteed to always return a result raised to 0, it doesn't require invoking an extra stack frame (entering the Math static function would), and it prevents underflow.

In the rare event that X is close to the minimum int, and y is sufficiently large enough, evaluating (x-y) would result in an underflow. The result would be "too large" of a negative number to fit in an int's space and would therefore roll into a nonsense (and probably positive) answer.

By forcing the if statement to guarantee no underflow exists, this solution is also more correct than the Math.max(...) solutions. However, most people don't care because they rarely deal with numbers that get close to causing overflows and underflows.

Upvotes: 9

Javed Akram
Javed Akram

Reputation: 15344

Use ternary operator ?:

int result = (x - y) > 0 ? (x - y) : 0;

Upvotes: 3

Related Questions