Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# absolute method in mathclass

Venkat Ramsimha
Ranch Hand
Posts: 127
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

Joe Sondow
Ranch Hand
Posts: 195
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.

Parameswaran Thangavel
Ranch Hand
Posts: 485
hi joe the negative number is -2147483648
am i right

Joe Sondow
Ranch Hand
Posts: 195
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.