Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String)
or Integer.parseInt(String)
and catch the NumberFormatException
.
If you want to allow numbers with decimal points, then use Float.valueOf(String)
or Float.parseFloat(String)
.
If you simply want to truncate the float
to an int
then either Float.intValue()
or two casts are equivalent. (The javadoc for intValue
explicitly states this.)
If you want to round to the nearest int
, use Math.round()
instead of a cast.
You should catch NumberFormatException
whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue()
is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
- that shouldn't be a concern for your use-case, and
- the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.