How can I cast an Object to an int in java?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re sure that this object is an
Integer:Or, starting from Java 7, you can equivalently write:
Beware, it can throw a
ClassCastExceptionif your object isn’t anIntegerand aNullPointerExceptionif your object isnull.This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
intis a primitive so it can’t be stored as anObject, the only way is to have anintconsidered/boxed as anIntegerthen stored as anObject.If your object is a
String, then you can use theInteger.valueOf()method to convert it into a simple int :It can throw a
NumberFormatExceptionif your object isn’t really aStringwith an integer as content.Resources :
On the same topic :