How to check if an object is convertible to another type?
Solution 1
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!
Solution 2
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 :)
Related videos on Youtube
Terence Ponce
My name is Terence Ponce. I'm a full stack developer with 10 YOE who is currently based in the Philippines. I've been working as a professional software developer since 2011 and I am usually employed for my knowledge in the following technologies: Elixir Ruby on Rails React Flutter React Native I have worked with various startups and mid-sized companies of varying industries throughout my career which makes me adaptable to whatever environment I am in. These experiences have also given me plenty of knowledge on the following topics: DevOps (Kubernetes, Infrastructure as Code, Monitoring) API development (GraphQL / REST) CI/CD (GitHub Actions, GitLab CI, Travis CI, etc.) Cloud Services (AWS / GCP) Writing internal and external documentation Integration with 3rd party services (payment gateways, mapping software, customer support software, etc.) Project Management I'm good at communication and collaboration. I'm fluent in English, both written and verbal. I'm also adaptable to any development workflows or tools as I have experienced most of them throughout my career.
Updated on June 04, 2022Comments
-
Terence Ponce almost 2 years
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
castableconvertible to type double and int, respectively? Is there a method or keyword in Java that does that already?-
BalusC over 13 yearsTo learn about casting, check this tutorial: download.oracle.com/javase/tutorial/java/IandI/subclasses.html
-
-
Terence Ponce over 13 yearsThanks for the clarification. I always thought casting and parsing are the same thing.
-
BalusC over 13 yearsDefinitely not. Both are however forms of conversion.