• Post Reply Bookmark Topic Watch Topic
  • New Topic

To Cast or Not To Cast  RSS feed

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!