Make a negative number positive

I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.

I'm sure there is very easy way of doing this - I just don't know how.


Solution 1:

Just call Math.abs. For example:

int x = Math.abs(-5);

Which will set x to 5.

Note that if you pass Integer.MIN_VALUE, the same value (still negative) will be returned, as the range of int does not allow the positive equivalent to be represented.

Solution 2:

The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:

number = (number < 0 ? -number : number);

or

if (number < 0)
    number = -number;