• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

To Cast or Not To Cast

 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I've a "long" variable and would like to create an "Integer" object with that.
Basically, I've 2 good options; ie: 1) cast the "long" object to "int" or 2) convert the "long" to "String" with String.valueOf() since "Integer" constructor do accept String object.
The 2 methods produce the same result but I'm just wondering in terms of good programming, should we avoid using the casting method?
Thanks in advance.
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
choices...
the second option might throw a runtime NumberFormatException if the String representation of the long is > Integer.MAX_VALUE, or < Integer.MIN_VALUE. the first option never will, because the numeric cast will never throw an exception. so use the cast if don't care if the number is too big/small for an int. however, if you use the cast, bear in mind that a very big long will possibly become negative as an int:

i would be tempted to test the long value to see if it fits as an int, before you cast it or use the second option. after that it really depends on performance needs (a cast in the Integer constructor will be quicker than using the String constructor, which calls parseInt with a radix of 10), and code clarity - some folk prefer exception handling for style reasons.
hope this helps
peter
reply
    Bookmark Topic Watch Topic
  • New Topic