Java – Double the trouble casting integers

Java has the ability to convert between data types. This occurs automatically if the data type can be safely converted into the new data type. So for example byte can be safely converted to short and short to int and so on. This is because the entire data stored in the lower data type type can safely stored in the new data type. However moving back the other way requires the programmer to explicitly cast as the desired data type using the following syntax: int a = (int) afloat.

I can hear you asking if the data type cannot automatically and safely convert then what is lost when explicit casting occurs. In the case of float or double back to integer the fraction is dropped. So 3.2, 3.4, 3.6, and 3.9 will all convert to an int value of 3, which is something to keep in mind. Especially if you are attemping to increment an integer value by let’s say 30% and then converting back to integer. i.e. num = (int) num * 1.3. So in this case if num falls below 4 it will never increment. To get around this use the rounding function in the Math Class: Math.round. eg. Math.round(3*1.3) will give integer value of 4. Of course even with rounding an integer with a value of 1 will never increment unless the increase is 50% or greater.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • Facebook
  • Twitter
  • Google Bookmarks

1 thought on “Java – Double the trouble casting integers

Leave a Reply

Your email address will not be published. Required fields are marked *