Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Math.abs()

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q24
What will be the result of attempting to complie & run the following code?
public class ADirtyOne
{
public static void main(String args[])
{
System.out.println(Math.abs(Integer.MIN_VALUE));
}
}
(a)Causes a compilation error
(b)Causes no error and the value printed on the screen is less than zero.
(c)Causes no error and the value printed on the screen is one more than the Integer.MAX_VALUE
(d)Will throw a runtime exception due to overflow - Integer.MAX_VALUE is less in magnitude than Integer.MIN_VALUE.

The answer is (b).
Java API Quote:
***************
"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."
An absolute +ve value is displayed in the case of Byte.MIN_VALUE & Short.MIN_VALUE.Why not so in the case of an int.???
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has got to do with the signed or unsigned
primitive types..... Byte does not store the sign bit
 
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reason for byte and short works because they are converted to "int" before the operation. "static int abs(int i)", it takes "int" as argument, if you pass in byte or short, they are implicitly converted to integer.
Both byte and short are signed, meaning they have sign bits. The only unsigned primitive is char.
 
Can you hear that? That's my theme music. I don't know where it comes from. Check under this tiny ad:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic