Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Object to Int (http://www.programmingforums.org/showthread.php?t=14635)

kruptof Nov 28th, 2007 12:55 PM

Object to Int
 
I am doing one of my Java assignments and I need to pass a method an int but I am receiving the data as an Object, is it possible to convert an Object to an int.

I will just demonstrate what I mean because I can't post my actual code.
:

public void A(Object o)
{
      //call B with the given data
      //do something
}
public void B(int i)
{
      //do something
}


titaniumdecoy Nov 28th, 2007 1:56 PM

Re: Object to Int
 
You need to know what the object is an instance of. Assuming it is an Integer, you can call the intValue() method to convert it to an int.

Infinite Recursion Nov 28th, 2007 2:14 PM

Re: Object to Int
 
test

null_ptr0 Nov 28th, 2007 4:26 PM

Re: Object to Int
 
Object is, haha, an object type, while int is a primitive type. You cannot translate objects to ints through direct casts; but if the object is of Integer, you could access and call the member method intValue() which returns the actual integer value being wrapped.
Example:
:

public void A(Object o) {
  if(o instanceof Integer)
        B(((Integer) o).intValue());
  else
        throw new IllegalArgumentException();
}

public void B(int i) {
    /*
        code is here
    */
}



All times are GMT -5. The time now is 3:39 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC