# Math.abs Confusion

Akhilesh Yadav

Ranch Hand

Posts: 46

posted 9 years ago

class s{

public static void main(String [] args){

System.out.println(Math.abs(-2147483648));

System.out.println(Math.abs(-2147483647));

}

}

out put is

-2147483648

2147483647

why the out put is difference ?

[ January 11, 2007: Message edited by: Akhilesh Yadav ]

public static void main(String [] args){

System.out.println(Math.abs(-2147483648));

System.out.println(Math.abs(-2147483647));

}

}

out put is

-2147483648

2147483647

why the out put is difference ?

[ January 11, 2007: Message edited by: Akhilesh Yadav ]

Tanakorn Numrubporn

Ranch Hand

Posts: 81

posted 9 years ago

the API doc of Math class in abs(int a) static method is said that:

It told you that if you use Math.abs(Integer.MIN_VALUE) you will get the result equal Integer.MIN_VALUE, which equal -2147483648.

But if you change the problem statement from:

System.out.println(Math.abs(-2147483648));

TO

System.out.println(Math.abs(-2147483648L));

The result is will become to 2147483648, which is not the negative value, you know why. Please go to see API and you will get enlightenment.

Cheers

Tanakorn

Originally posted by Akhilesh Yadav:

class s{

public static void main(String [] args){

System.out.println(Math.abs(-2147483648));

System.out.println(Math.abs(-2147483647));

}

}

out put is

-2147483648

2147483647

why the out put is difference ?

the API doc of Math class in abs(int a) static method is said that:

*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.*

It told you that if you use Math.abs(Integer.MIN_VALUE) you will get the result equal Integer.MIN_VALUE, which equal -2147483648.

But if you change the problem statement from:

System.out.println(Math.abs(-2147483648));

TO

System.out.println(Math.abs(-2147483648L));

The result is will become to 2147483648, which is not the negative value, you know why. Please go to see API and you will get enlightenment.

Cheers

Tanakorn