# Math.abs()

Thomas Markl
Ranch Hand
Posts: 192
Why is Math.abs(Integer.MIN_VALUE) not a positive value like Math.abs(Byte.MIN_VALUE) is?
class Q009 {
public static void main ( String args [ ] ) {
System.out.println ( ( Math.abs( Integer.MIN_VALUE ) ) );
System.out.println ( Integer.MIN_VALUE );

System.out.println ( ( Math.abs( Byte.MIN_VALUE ) ) );
System.out.println ( Byte.MIN_VALUE );
}
}

Thomas Markl
Ranch Hand
Posts: 192
Sorry, I forgot to state the result:
C:\Java\EigeneJavaProgramme>java Q009
-2147483648
-2147483648
128
-128
Why is Math.abs(Integer.MIN_VALUE) not positive?

Igor Ko
Ranch Hand
Posts: 90
I think explanation here is internal
representation of signed integer in computer.
For example byte range is
-128 -127 .... -1, 0, 1 ... 127.
Operation -x is bits inversion of x, plus one.
It works well, ... but min value -128 ==
1000 0000 in binary form, convert into itself:
bits inversion is 0111 1111, plus one is 1000 0000.
It's problem of such number representation -
no abs (positive number) for min negative number.
So you can't get abs of -128,
the "must be" result 128 is simple out of byte range.
It's the same for min value of other integer types:
short (two bytes), int (4 bytes) and long(8 bytes)
[ October 28, 2002: Message edited by: Igor K ]
[ October 28, 2002: Message edited by: Igor K ]

Ilja Preuss
author
Sheriff
Posts: 14112
With other words: 2147483648 is not an int, therefore you get an overflow.
Try Math.abs((long)Integer.MIN_VALUE) instead, this will call the overloaded method with a long as return value.

Dirk Schreckmann
Sheriff
Posts: 7023
Section 4.2.2 of the JLS mentions that "[t]he built-in integer operators do not indicate overflow or underflow in any way." So what the heck does that mean exactly, right?
A couple of sources you may want to take a look at:
• http://math.hws.edu/javanotes/c9/s1.html - The last section of the page
• Roedy Green's Overflow Java Gotcha Explanation which highlights the problem, but doesn't really explain the situation in detail (but it's still a nice list of gotchas to read up on).
• Roedy Green's Java Glossary on overflow
• Does any of that help to clarify the situation?