This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

abs() method of Math class

 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends;

We know the abs()method of Math class returns the absulute val of the num.

but if we try


class Test{

public static void main(String args[]){
System.out.println((Math.abs(Integer.MIN_VALUE)));
System.out.println((Math.abs(-2147483648)));
System.out.println((Math.abs(-4)));
}
}

gives an o/p as:

-2147483648
-2147483648
4

Why?

is it because, the no. is very big no. & abs() can't take such big no for operation?
 
Mishra Anshu
Ranch Hand
Posts: 224
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648

I think you are expecting abs(Integer.MIN_VALUE) = 2147483648, but that can't be represented as it exceeds the Integer's range.

So,the value is -2147483648 which you may verify
by printing

System.out.println(Integer.MAX_VALUE + 1);
 
Timmy Marks
Ranch Hand
Posts: 226
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer.MIN_VALUE is represented in binary as 10000000000000000000000000000000. Since this is a negative number, the absolute value will be -1 * the number - The twos complement is the ones complement plus one - The ones complement will be 01111111111111111111111111111111 and when we add 1 to it, we get 10000000000000000000000000000000 (which is Integer.MIN_VALUE again!), so the problem is not that abs() cannot handle such large numbers, the problem is that ints are 32 bits.
 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys.
I got the ans.

bye ,
take care.

shubha.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys -

just a reminder - if you're studying for the 1.5 exam, this topic is not on the exam! yeah!

- Bert
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic