Is there any way to find the absolute value of a number without using the Math.abs() method in java.
-
26And the reason for not wanting to use that method is ... – Thilo Jun 13 '12 at 10:44
-
Is the number specified as Integral type, int, byte, short, long or is it a floating point (float, double) or a boxing class (Integer, Double, ...) or BigDecimal, BigInteger or something else? Unspecified? – user unknown Jun 13 '12 at 12:49
-
I need to use it in a loop. So i am searching for any other best Approach. – Theja Jun 14 '12 at 04:09
-
1you can use Math.abs in a loop. Don't micro-optimize. The JVM will usually make it fast enough. If you really think it is too slow, measure it. – Thilo Jun 14 '12 at 09:58
-
@Thilo I checked it. working good, i am trying to find different approaches so i can use best approach as per my need. – Theja Jun 14 '12 at 10:30
10 Answers
If you look inside Math.abs you can probably find the best answer:
Eg, for floats:
/*
* Returns the absolute value of a {@code float} value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
* Special cases:
* <ul><li>If the argument is positive zero or negative zero, the
* result is positive zero.
* <li>If the argument is infinite, the result is positive infinity.
* <li>If the argument is NaN, the result is NaN.</ul>
* In other words, the result is the same as the value of the expression:
* <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
*
* @param a the argument whose absolute value is to be determined
* @return the absolute value of the argument.
*/
public static float abs(float a) {
return (a <= 0.0F) ? 0.0F - a : a;
}

- 64,482
- 16
- 119
- 213

- 1,911
- 13
- 15
Yes:
abs_number = (number < 0) ? -number : number;
For integers, this works fine (except for Integer.MIN_VALUE
, whose absolute value cannot be represented as an int
).
For floating-point numbers, things are more subtle. For example, this method -- and all other methods posted thus far -- won't handle the negative zero correctly.
To avoid having to deal with such subtleties yourself, my advice would be to stick to Math.abs()
.

- 486,780
- 108
- 951
- 1,012
-
Good point about floating points. It's not too bad, though, here is the source for the double abs from java.lang.Math: `return (a <= 0.0D) ? 0.0D - a : a;` and the float version looks similar. – Thilo Jun 13 '12 at 10:52
-
@Thilo: The real point here is that floating-point math is full of subtleties. Unless there is a truly compelling argument otherwise, one should just stick to using the standard functions. – NPE Jun 13 '12 at 10:54
-
I know a testcase where this fails for Int, Long, Byte and Short too. – user unknown Jun 13 '12 at 12:42
-
@userunknown: Of course, but that's a property of the two's complement representation of integers, not of the method for computing `abs()`. – NPE Jun 13 '12 at 12:44
-
@aix: ? So that's a reason to ignore it? The 2-complement is guilty? – user unknown Jun 13 '12 at 12:45
-
@userunknown: If you read the question, the OP is looking to emulate `Math.abs()`. The code in my answer behaves **exactly** like `Math.abs(int)` for `Integer.MIN_VALUE`. – NPE Jun 13 '12 at 12:51
-
@aix: Maybe you visit us [in Chat?](http://chat.stackoverflow.com/rooms/12491/discussion-between-user-unknown-and-tibtof)? I don't read 'emulate Math.abs' - I read without using Math.abs. And I would say that the method in the Javalibs is broken for that specific reason. – user unknown Jun 13 '12 at 13:46
-
@userunknown: Thanks for the invitation, but this issue is simply not important enough to me personally to justify investing time into debating it further. – NPE Jun 13 '12 at 13:48
-
Correct code should always be important - I guess you're not giving the best example to a beginner. :) Hiding behind the authority of java.lang.Math.abs isn't good habit, imho, too. But I can't force you. – user unknown Jun 13 '12 at 14:44
Like this:
if (number < 0) {
number *= -1;
}

- 7,857
- 1
- 32
- 49
-
-
-
2@userunknown The positive of a MIN_VALUE cannot be contained in the same type of data, so this is not a flow. Have a look here: http://en.wikipedia.org/wiki/Two%27s_complement – tibtof Jun 13 '12 at 13:14
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/12491/discussion-between-user-unknown-and-tibtof) – user unknown Jun 13 '12 at 13:24
Since Java is a statically typed language, I would expect that a abs-method which takes an int returns an int, if it expects a float returns a float, for a Double, return a Double. Maybe it could return always the boxed or unboxed type for doubles and Doubles and so on.
So you need one method per type, but now you have a new problem: For byte, short, int, long the range for negative values is 1 bigger than for positive values.
So what should be returned for the method
byte abs (byte in) {
// @todo
}
If the user calls abs on -128? You could always return the next bigger type so that the range is guaranteed to fit to all possible input values. This will lead to problems for long, where no normal bigger type exists, and make the user always cast the value down after testing - maybe a hassle.
The second option is to throw an arithmetic exception. This will prevent casting and checking the return type for situations where the input is known to be limited, such that X.MIN_VALUE can't happen. Think of MONTH, represented as int.
byte abs (byte in) throws ArithmeticException {
if (in == Byte.MIN_VALUE) throw new ArithmeticException ("abs called on Byte.MIN_VALUE");
return (in < 0) ? (byte) -in : in;
}
The "let's ignore the rare cases of MIN_VALUE" habit is not an option. First make the code work - then make it fast. If the user needs a faster, but buggy solution, he should write it himself. The simplest solution that might work means: simple, but not too simple.
Since the code doesn't rely on state, the method can and should be made static. This allows for a quick test:
public static void main (String args []) {
System.out.println (abs(new Byte ( "7")));
System.out.println (abs(new Byte ("-7")));
System.out.println (abs((byte) 7));
System.out.println (abs((byte) -7));
System.out.println (abs(new Byte ( "127")));
try
{
System.out.println (abs(new Byte ("-128")));
}
catch (ArithmeticException ae)
{
System.out.println ("Integer: " + Math.abs (new Integer ("-128")));
}
System.out.println (abs((byte) 127));
System.out.println (abs((byte) -128));
}
I catch the first exception and let it run into the second, just for demonstration.
There is a bad habit in programming, which is that programmers care much more for fast than for correct code. What a pity!
If you're curious why there is one more negative than positive value, I have a diagram for you.

- 1
- 1

- 35,537
- 11
- 75
- 121
Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.
(x + (x >> 31)) ^ (x >> 31);
This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

- 1,788
- 2
- 17
- 27
-
Yes, this is excellent if you want to confuse the hell out of a lot of people, especially if you name the function a() or something similarly vague – niken Jun 20 '16 at 14:09
In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.
(int)(((long)x*x - 1)%(double)x + 1);
Because Java treats a%b
as a - a/b * b
, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x
will equal abs(x)-1
; type casting of "long" is to prevent overflow and double
allows dividing by zero.
Again, x = Integer.MIN_VALUE
will cause overflow due to subtracting 1.

- 239,200
- 50
- 490
- 574

- 631
- 6
- 6
Here is a one-line solution that will return the absolute value of a number:
abs_number = (num < 0) ? -num : num;

- 10,555
- 15
- 68
- 131

- 599
- 1
- 6
- 13
-num will equal to num for Integer.MIN_VALUE as
Integer.MIN_VALUE = Integer.MIN_VALUE * -1

- 347
- 3
- 8
Lets say if N is the number for which you want to calculate the absolute value(+ve number( without sign))
if (N < 0)
{
N = (-1) * N;
}
N will now return the Absolute value

- 5,977
- 2
- 24
- 25

- 73
- 1