[java] How to cast an Object to an int

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

This question is related to java object casting integer

The answer is


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<>();

    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


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.


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

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;

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.


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.


so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/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:


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

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


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.


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

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

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.


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);
  }
}

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


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));

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


Finally, the best implementation for your specification was found.

public int tellMyNumber(Object any) {
    return 42;
}

int i = (Integer) object; //Type is Integer.

int i = Integer.parseInt((String)object); //Type is String.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?