Convert Object to Integer in java

I found this very tricky. I  first converted Object to String then used java’s Integer.parseInt(String s) method to change String to Integer. Then I added int value to the converted value, wihch verifies the object has been successfully converted to int.



public class  ObjectToInt {
public static void main(String args[]) {
Object object = "123";

		int value = 0 ; //int value = zero

/** Type Cast Object to String */
String tempString = (String) object;

/** use Integer.parseInt(String s) method to change to   int value */

		value = Integer.parseInt((String)object);

		//Finally Check the value
	System.out.print(value+2);
    }
}

3 Replies to “Convert Object to Integer in java”

  1. If my method takes object as argument then how to convert that object to integer. You don’t know what could be the type of object.

    1. It’s been long time since I wrote this. I can’t remember exactly how this work. But looking at code, as long as you can type cast Object to String, it should still be the same. You should still be able to type cast to integer.

Leave a Reply

Your email address will not be published. Required fields are marked *