How to cast an Object to an int
Asked Answered
S

22

268

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

Shelashelagh answered 7/9, 2010 at 18:15 Comment(4)
What do you really want to do? If the Object isn't an Integer, I'm not sure what your are expecting from your cast.Aeroplane
first check with instanceof keyword . if true then cast it.Eaglet
Aww. I just wanted to have enum members to cast to specific integer values, so that I can have enums for winapi constants. msdn.microsoft.com/en-us/library/windows/desktop/…Groom
@TomášZato You can do that (sort of), just define a field in your enum to hold the integer value (say, intValue), create a constructor for your enum that sets the intValue, have your enum constants invoke that constructor, and add a getter for intValue. Then, instead of casting, call the getter.Bolger
S
440

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 :

Schroer answered 7/9, 2010 at 18:19 Comment(8)
Are you sure about the NullPointerException? I thought that a null Object would just yield a null Integer....Libbey
The NullPointerException will occur during the unboxing of Integer into intSchroer
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.Climax
@Steve Kuo, Yep, exactly what I'm saying. That's why I didn't use the "cast" word.Schroer
@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".Lithium
@Colin first check with instanceof keyword . if true then cast it.Eaglet
Also, unboxing to promitives, always should check first if the object is not null.Bailsman
Use rather int i = Integer.valueOf(object.toString())Gouda
W
26

Scenario 1: simple case

If it's guaranteed that your object is an Integer, this is the simple way:

int x = (Integer)yourObject;

Scenario 2: any numerical object

In Java Integer, Long, BigInteger etc. all implement the Number interface which has a method named intValue. Any other custom types with a numerical aspect should also implement Number (for example: Age implements Number). So you can:

int x = ((Number)yourObject).intValue();

Scenario 3: parse numerical text

When you accept user input from command line (or text field etc.) you get it as a String. In this case you can use Integer.parseInt(String string):

String input = someBuffer.readLine();
int x = Integer.parseInt(input);

If you get input as Object, you can use (String)input, or, if it can have an other textual type, input.toString():

int x = Integer.parseInt(input.toString());

Scenario 4: identity hash

In Java there are no pointers. However Object has a pointer-like default implementation for hashCode(), which is directly available via System.identityHashCode(Object o). So you can:

int x = System.identityHashCode(yourObject);

Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.

You can also use object.hashCode(), but it can be type specific.

Scenario 5: unique index

In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:

class ObjectIndexer {
    
    private int index = 0;
    
    private Map<Object, Integer> map = new WeakHashMap<>();
    //                               or:
    //                                 new WeakIdentityHashMap<>();
    
    public int indexFor(Object object) {
        if (map.containsKey(object)) {
            return map.get(object);
        } else {
            index++;
            map.put(object, index);
            return index;
        }
    }
    
}

Usage:

ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject);    // 1
int y = indexer.indexFor(new Object());  // 2
int z = indexer.indexFor(yourObject);    // 1

Scenario 6: enum member

In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal(), for example:

enum Foo { BAR, BAZ, QUX }

// ...

Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1

enter image description here

Wooden answered 16/10, 2015 at 13:54 Comment(0)
R
20

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.

Rooney answered 7/9, 2010 at 18:17 Comment(4)
If obj is null it will throw a NullPointerException.Schroer
and a ClassCastException if it's not an Integer object.Rooney
No need to invoke intValue for autoboxing will invoke it for you.Madder
intValue is much clearer especially considering the beginner confusion between int being interchangeable with Integer.Climax
B
13
@Deprecated
public static int toInt(Object obj)
{
    if (obj instanceof String)
    {
         return Integer.parseInt((String) obj);
    } else if (obj instanceof Number)
    {
         return ((Number) 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.

Buote answered 7/9, 2010 at 18:51 Comment(3)
Isn't it @Deprecated (e in stead of a)? :) Nice method though, makes no assumptions on the type of the object.Ogbomosho
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.Ogbomosho
You missed support for Boolean types: public static int toInt(Object obj) { if (obj instanceof Boolean) { return ((boolean) obj) ? 1 : 0; } else if (obj instanceof String) { return Integer.parseInt((String) obj); } else if (obj instanceof Number) { return ((Number) obj).intValue(); } throw new IllegalArgumentException("This Object doesn't represent an int"); }Ghibelline
L
4

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.

Libbey answered 7/9, 2010 at 18:17 Comment(0)
M
4

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
Madder answered 7/9, 2010 at 18:33 Comment(0)
M
4

I use a one-liner when processing data from GSON:

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
Mane answered 12/12, 2013 at 22:0 Comment(2)
Its a lengthy process. Just do (int)Object instead of Double.valueOf(object.toString()).intValue(). This works only for numbers, thats what we needed.Elsaelsbeth
@SudhakarK: (int) Object does only work if your object is a Integer. This oneliner also supports String numbers; E.G. "332".Bungalow
O
2

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

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

Ogbomosho answered 7/9, 2010 at 18:17 Comment(5)
There's auto boxing/unboxing since Java 5.Prototrophic
@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.Lithium
(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.Lithium
@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...)Prototrophic
@Prototrophic The trickypart of autoboxing it that it can give you unexpected NullPointerExceptions.Ogbomosho
R
2

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
Ripley answered 7/9, 2010 at 18:18 Comment(2)
This assumes that the object is an integer which it almost certainly is not. Probably want's the string solution ala CoronautsMarxmarxian
How could it compile when you are casting an object into Object and then trying to set it to an Integer variable.Downer
H
2

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:

Hymenopterous answered 7/9, 2010 at 18:20 Comment(0)
L
2
int i = (Integer) object; //Type is Integer.

int i = Integer.parseInt((String)object); //Type is String.
Lumbye answered 7/9, 2010 at 18:36 Comment(0)
D
2

For Example Object variable; hastaId

Object hastaId = session.getAttribute("hastaID");

For Example Cast an Object to an int,hastaID

int hastaID=Integer.parseInt(String.valueOf(hastaId));
Dare answered 24/12, 2014 at 14:59 Comment(0)
T
1

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.

Therefor answered 7/9, 2010 at 18:18 Comment(1)
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.Biernat
C
1

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.

Catalyze answered 7/9, 2010 at 19:15 Comment(0)
L
1
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
    ArrayList list = null;
    Statement statement = conn.createStatement();
    ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
    while (result.next()) {
        list.add(result.getInt(1));
    }
    statement.close();
    int id[] = new int[list.size()];
    for (int i = 0; i < id.length; i++) {
        try {
            id[i] = ((Integer) list.get(i)).intValue();
        } catch(NullPointerException ne) {
        } catch(ClassCastException ch) {}
    }
    return id;
}
// enter code here

This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.

Liber answered 21/5, 2014 at 6:30 Comment(1)
Please explain your answerCryohydrate
S
0

Refer This code:

public class sample 
{
  public static void main(String[] args) 
  {
    Object obj=new Object();
    int a=10,b=0;
    obj=a;
    b=(int)obj;

    System.out.println("Object="+obj+"\nB="+b);
  }
}
Sillsby answered 2/10, 2014 at 12:57 Comment(0)
T
0
so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/2;
Toughminded answered 27/1, 2019 at 20:45 Comment(1)
This shows a situation where the casting is required and I will add the error as well that actually shows up with this situation. Its hard for a new coder to figure out the actual implementation if there is no example. I hope this example helps themToughminded
M
0

We could cast an object to Integer in Java using below code.

int value = Integer.parseInt(object.toString());

Mission answered 6/6, 2022 at 6:38 Comment(0)
J
0

If you want to convert string-object into integer... you can simply pass as:

 int id = Integer.valueOf((String) object_name);

Hope this will be helpful :-)

Jeffjeffcoat answered 12/10, 2022 at 11:44 Comment(1)
Your solution has already been mentioned in the accepted answer.Weasel
L
0
Integer x = 11
int y = x.intValue();
System.out.println("int value"+ y);
Livy answered 26/2, 2023 at 17:3 Comment(1)
This just repeats the solution from multiple other answers without adding anything new.Mudlark
W
-3

Finally, the best implementation for your specification was found.

public int tellMyNumber(Object any) {
    return 42;
}
Wooden answered 5/12, 2019 at 19:7 Comment(0)
E
-4

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

Eaglet answered 8/9, 2010 at 11:6 Comment(1)
I used this and now im wondering how to solve the 'Boxed value is unboxed then immeditaley reboxed' on that line. (Due to spotbugs checks) so now i'm wondering how to solve it better.Ensile

© 2022 - 2024 — McMap. All rights reserved.