• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why Math.abs() is giving negative output??????

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.lang.Math;
class MathAbsSup
{
public static void main(String args[])
{
System.out.println(Math.abs(Integer.MIN_VALUE));

}
}
//Why Math.abs() is giving negative output??? (-2147483648)
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi,
I'm getting the same result. check the Integer Leteral range.

Integer.MIN_VALUE = -2147483648
Integer.MAX_VALUE = 2147483647
1. (Math.abs(Integer.MIN_VALUE)) // prints -2147483648
2. (Math.abs(-2147483648)) // prints -2147483648
3. (Math.abs(-2147483647)) // prints 2147483647

line 1 and 2 's output as per abs function,it should be positive
2147483648 , but the value it is out of range.

Decimal Int literals must be in the range -2147483648
to 2147483647.

Best Regards
Arvind
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Munish,
The answer is in the API; check <code>java.lang.Math.abs(Integer)</code>


Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value,
the result is that same value, which is negative.


Hope that helps.
Jane
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To get the desired effect. Cast it to long first. For instance,
Math.abs((long)Integer.MIN_VALUE) will return 2147483648. The absolute value of the MIN_VALUE exceeds the stoarge capacity of the type so by increasing the capacity, you're able to get the absolute value.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic