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, which verifies the object has been successfully converted to int.

Save the file as
1. Compile it javac
2. Run it java ObjecttoInt
3.You should get 125 as result.

Java Object to Integer

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

Samundra Shrestha

I work as fullstack developer. Having spent more than 5 years in the web development technologies, I aspire to create an environment where we can share, learn and grow together.

One thought on “Convert Object to Integer in java

  • May 8, 2016 at 3:19 PM

    That’s a shame, it doesn’t work. I get the error message of

    Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at Homework.Project.main(


Leave a Reply

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