How can I cast an Object to an int in java?
If you're sure that this object is an
int i = (Integer) object;
Or, starting from Java 7, you can equivalently write:
int i = (int) object;
This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.
int is a primitive so it can't be stored as an
Object, the only way is to have an
int considered/boxed as an
Integer then stored as an
If your object is a
String, then you can use the
Integer.valueOf() method to convert it into a simple int :
int i = Integer.valueOf((String) object);
It can throw a
NumberFormatException if your object isn't really a
String with an integer as content.
On the same topic :