aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes absolute method in mathclass Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "absolute method in mathclass" Watch "absolute method in mathclass" New topic
Author

absolute method in mathclass

Venkat Ramsimha
Ranch Hand

Joined: Dec 28, 2004
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

Joined: Apr 10, 2005
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.


SCJA 1.0 (98%), SCJP 1.4 (98%)
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi joe the negative number is -2147483648
am i right
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: absolute method in mathclass