Let's say I have two string objects: "25000.00", and "1234" that my program gets at run time. How do I check if they are castable convertible to type double and int, respectively? Is there a method or keyword in Java that does that already?
You can use the Integer.parseInt
or Double.parseDouble
static methods to do this. Each of these methods takes in a String
and converts them to an int
or double
as appropriate. You can check whether the string is convertible by calling this function. If the conversion is possible, it will be performed. Otherwise, the methods will throw NumberFormatException
s, which you can catch and respond to. For example:
try {
int value = Integer.parseInt(myString);
// Yes! An integer.
} catch (NumberFormatException nfe) {
// Not an integer
}
Hope this helps!
Just to clarify: String
is never castable to Double
or Integer
.
However, you can parse a String as a number using the Double.parseDouble
and Integer.parseInt
methods. If they are not parsable then a NumberFormatException
will be thrown. You can catch that and handle it appropriately.
Casting and parsing are quite different things.
EDIT: I see @BalusC has edited the question and changed "cast" to "convert". I guess my comments are redundant now :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With