Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is convertible to another type?

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?

like image 423
Terence Ponce Avatar asked Jan 12 '11 00:01

Terence Ponce


2 Answers

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 NumberFormatExceptions, 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!

like image 137
templatetypedef Avatar answered Sep 22 '22 10:09

templatetypedef


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 :)

like image 21
Cameron Skinner Avatar answered Sep 22 '22 10:09

Cameron Skinner