views:

268

answers:

12

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

+3  A: 

You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.

Etienne de Martel
+5  A: 

Assuming the object is an Integer object, then you can do this:

int i = ((Integer) obj).intValue();

If the object isn't an Integer object, then you have to detect the type and convert it based on its type.

Erick Robertson
If obj is null it will throw a NullPointerException.
Colin Hebert
and a ClassCastException if it's not an Integer object.
Erick Robertson
No need to invoke `intValue` for autoboxing will invoke it for you.
OscarRyz
`intValue` is much clearer especially considering the beginner confusion between `int` being interchangeable with `Integer`.
Steve Kuo
+1  A: 

You can't. An int is not an Object.

Integer is an object though, but I doubt that's what you mean.

extraneon
There's auto boxing/unboxing since Java 5.
Bruno
@Bruno: You can't cast an Object to an int. You can cast an Object to an Integer and then assign it to an int and it will magically autounbox. But you can't cast an Object to an int.
Jay
(continued) Personally, I think people create a lot of bad code relying on autoboxing. Like, I saw a statement the other day, "Double amount=(Double.parseDouble(stringAmount)).doubleValue();". That is, he parsed a String to get a double primitive, then executed a function against this, which forced the compiler to autobox it into a Double object, but the function was doubleValue which extracted the double primitive, which he then assigned to a Double object thus forcing an autobox. That is, he converted from primitive to object to primitive to object, 3 conversions.
Jay
@Jay, agreed on 1st comment (sorry I wasn't clear myself). Regarding too many conversion, you're right too, but I get the impression that the JIT compiler can cope with that quite well, so it shouldn't matter that much in practice (that doesn't necessarily make it an excuse for bad code...)
Bruno
@Bruno The trickypart of autoboxing it that it can give you unexpected NullPointerExceptions.
extraneon
A: 

Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.

 Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class

 int num = i; //Java 1.5 or higher
Tom
This assumes that the object is an integer which it almost certainly is not. Probably want's the string solution ala Coronauts
Bill K
And won't compile.
Ricky Clarkson
@Ricky What part? 1.4, 1.5?
Tom
@Tom How could it compile when you are casting an object into Object and then trying to set it to an Integer variable.
Carlos
@Khilon. Thanks, fixed it
Tom
A: 

If you mean cast a String to int, use Integer.valueOf("123").

You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.

Coronatus
Don't use `Integer.valueOf("123")` if all you need is a primitive instead use `Integer.parseInt("123")` because **valueOf** method causes an unnecessary unboxing.
krmby
+11  A: 

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

int i = (Integer) 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 :

Colin Hebert
Are you sure about the NullPointerException? I thought that a null Object would just yield a null Integer....
Etienne de Martel
The `NullPointerException` will occur during the unboxing of `Integer` into `int`
Colin Hebert
Ah, yeah, my brain ignored the left part of the assignment...
Etienne de Martel
Downvoter, any explanation ?
Colin Hebert
You're not casting to an int, no Object can ever be cast to an int. You're actually to Integer and then autoboxing to an int.
Steve Kuo
@Steve Kuo, Yep, exactly what I'm saying. That's why I didn't use the "cast" word.
Colin Hebert
@Etienne: You can cast a null Object to an Integer, thus getting a null Integer. But when you try to extract the int from it, you'll get a null pointer exception. There's no such thing as a "null int".
Jay
@Colin first check with instanceof keyword . if true then cast it.
Suresh S
A: 

If the Object was originally been instantiated as an Integer, then you can downcast it to an int using the cast operator (Subtype).

Object object = new Integer(10);
int i = (Integer) object;

Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i as Integer instead and then call intValue() on it.

But if it initially wasn't created as an Integer at all, then you can't downcast like that. It would result in a ClassCastException with the original classname in the message. If the object's toString() representation as obtained by String#valueOf() denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf() or new Integer() for this.

Object object = "10";
int i = Integer.valueOf(String.valueOf(object));

See also:

BalusC
A: 

Answer:

int i = ( Integer ) yourObject;

If, your object is an integer already, it will run smoothly. ie:

Object yourObject = 1;
//  cast here

or

Object yourObject = new Integer(1);
//  cast here

etc.

If your object is anything else, you would need to convert it ( if possible ) to an int first:

String s = "1";
Object yourObject = Integer.parseInt(s);
//  cast here

Or

String s = "1";
Object yourObject = Integer.valueOf( s );
//  cast here
OscarRyz
A: 
int i = (Integer) object; //Type is Integer.

int i = Integer.parseInt((String)object); //Type is String.
krmby
+2  A: 
@Deprecated
public static int toInt(Object obj)
{
    if (obj instanceof String)
    {
         return Integer.parseInt((String) obj);
    } else if (obj instanceof Integer)
    {
         return ((Integer) obj).intValue();
    } else
    {
         String toString = obj.toString();
         if (toString.matches("-?\d+"))
         {
              return Integer.parseInt(toString);
         }
         throw new IllegalArgumentException("This Object doesn't represent an int");
    }
}

As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.

Martijn Courteaux
Isn't it @Deprecated (e in stead of a)? :) Nice method though, makes no assumptions on the type of the object.
extraneon
@extraneon: Yes, indeed, I will fix it.
Martijn Courteaux
By the way, your regex doesn't take radix hex or oct into account. ToInt is a smart method. Bettere to try and catch NumberFormatExcepytion.
extraneon
+1  A: 

I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.

Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.

romacafe
A: 

first check with instanceof keyword . if true then cast it.

Suresh S