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 ObjectToInt.java
1. Compile it javac ObjectToInt.java
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
	System.out.print(value+2);
    }
}

One thought on “Convert Object to Integer in java

  1. Adam

    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(Project.java:146)

    Reply

Leave a Reply

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