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

# absolute method in mathclass

Ranch Hand
Posts: 127
• Number of slices to send:
Optional 'thank-you' note:
public class MathClassImp1
{
public static void main(String[] args)
{
System.out.println("" +Math.abs(-99));
System.out.println("" +Math.abs(99));

}
}

Hi All,
The output for both the above program is 99 in both the cases.so wht is the
difference in giving the postive and negative values in the system.out println statements

Can anybody provide the explanation for the above

thanks&Cheers
venkat

Ranch Hand
Posts: 195
• Number of slices to send:
Optional 'thank-you' note:
The absolute value of a number is always non-negative. Basically, Math.abs drops the negative sign if there is a negative sign, and leaves the number positive if it already was positive. As you saw in the example you posted, the absolute value of -99 is 99, and the absolute value of 99 is also 99. Absolute value means to make the number non-negative.

I say non-negative instead of positive because the absolute value of 0 is 0, which is neither positive nor negative in pure mathematics. Aside from the 0 case, an absolute value yields a positive number in pure math. In Java, there is one other special case where Math.abs(int) returns a negative number, which is Math.abs(Integer.MIN_VALUE) which returns -2147483648 because +2147483648 isn't a possible value for an int.

Ranch Hand
Posts: 485
• Number of slices to send:
Optional 'thank-you' note:
hi joe the negative number is -2147483648
am i right

Joe Sondow
Ranch Hand
Posts: 195
• Number of slices to send:
Optional 'thank-you' note:
I'm not certain what you're asking, but -2147483648 is a negative number, yes. It's the lowest possible value for a Java int. It's what Integer.MIN_VALUE is equal to.

Each of these boolean expressions returns true:
Integer.MIN_VALUE == -2147483648
Math.abs(Integer.MIN_VALUE) == -2147483648
Math.abs(-2147483648) == -2147483648
Math.abs(-2147483648) == Integer.MIN_VALUE

This is the only int value that returns a negative value from Math.abs. All other int values passed to Math.abs(int) will return 0 or a positive value.

 Consider Paul's rocket mass heater.