Plus Ultra
Plus Ultra

Reputation: 139

What method in Java returns the absolute difference of two integers?

Is there a method in the Java Math class that returns the absolute difference of two integers?

int absDiff = 8 - 15;
int answer = 7;

Upvotes: 3

Views: 9612

Answers (3)

nmatt
nmatt

Reputation: 505

The previous answers all give the wrong result when the difference is above Integer.MAX_VALUE, for example when calculating the absolute difference between 2000000000 and -2000000000 (resulting in 294967296 instead of 4000000000). In that case the correct result cannot be represented by an int. The solution is to use long for the calculation and the result:

public static long absoluteDifference(int a, int b)
{
    return Math.abs((long) a - b);
}

In some situations it's also okay to round down any difference greater than Integer.MAX_VALUE to Integer.MAX_VALUE (saturation arithmetics):

public static int absoluteDifferenceSaturated(int a, int b)
{
    long absDiff = Math.abs((long) a - b);
    return absDiff > Integer.MAX_VALUE ? Integer.MAX_VALUE : Math.toIntExact(absDiff);
}

For calculating the absolute difference of two longs, you may have to resort to BigInteger:

public static BigInteger absoluteDifference(long a, long b)
{
    return BigInteger.valueOf(a).subtract(BigInteger.valueOf(b)).abs();
}

Upvotes: 0

Batek'S
Batek'S

Reputation: 150

You can use Math class abs method like below

int num1 = 8; 
int num2 = 15;
int answer = Math.abs(num1 - num2);

And You can do this thing by logically also like below

int num1 = 8;
int num2 = 15;
int answer = (num1 - num2) * -1;

Upvotes: 0

Lavish Kothari
Lavish Kothari

Reputation: 2331

There's no method in java.lang.Math class that takes 2 int args and returns the absolute difference. But you can simply do that using the following:

int a = 8;
int b = 15;
int absDiff = Math.abs(a - b);

Upvotes: 6

Related Questions