Search code examples
javaobjectcastinginteger

How to cast an Object to an int


How can I cast an Object to an int in java?


Solution

  • If you're sure that this object is an Integer :

    int i = (Integer) object;
    

    Or, starting from Java 7, you can equivalently write:

    int i = (int) object;
    

    Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

    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 Object.


    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.


    Resources :

    On the same topic :