• Register
0 votes


I am new in programming. I was doing my java practice. I wrote a code:

Object imObject = new String();
Integer i = (Integer) imObject;

This code gives me the following error:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at test.ClassCastExcetpionTest.main(ClassCastExcetpionTest.java:31)

I am newbee so I am confused about what is happening , Can anyone explain why is this happening?

10 7 2
6,060 points

Please log in or register to answer this question.

2 Answers

–1 vote


Solving ClassCastException can be very easy once you understand polymorphism in Java and difference between compile time and runtime things. ClassCastException are simple like NullPointerException just look the stack-trace and go to the line number. Many of advanced Java IDE like Eclipse and Netbeans will give you hyperlink to navigate till culprit line number in Java file. Now you know where exactly ClassCastException is coming and stack trace also told which object it was trying to cast,
Now you have to find, how that type of object comes and this could take some time based upon complexity of your java application. You can also prevent ClassCastException in Java by using Generics. Generics are designed to write type-safe code and provides compile time checks which tends to violate type-safety. By using Generics in Collection classes and other places you can safely minimize java.lang.ClassCastException in Java. That’s all on What is ClassCastException in Java and how to solve Exception in thread "main" java.lang.ClassCastException.
I highly recommend to use Generics while using any Collection classes or class which acts as container e.g. ThreadLocal in Java. Also write your own classes and method to take advantage of Generics to provide type-safety
as shown in this example of How to write parameterized class. It’s also a good idea to refresh your knowledge on type-casting in Java.


11 6 4
34,950 points
0 votes


Why this is not possible?

Since String and Integer are not in the similar Object hierarchy.

     /      \
    /        \
String     Integer

The casting which you are attempting, performs only in case they are in the same hierarchy, for example


In this instance, (A) objB or (Object) objB or (Object) objA will perform.

Therefore, as others have mentioned meanwhile, to convert an integer to string use:

String.valueOf(integer), or Integer.toString(integer) for primitive,


Integer.toString() for the object.

No, Integer and String are different types. To convert an integer to string employ: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object.

For int types employ:

int myInteger = 1;
String myString = Integer.toString(myInteger);

For Integer types employ:

Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();

No. Each object can be casted to an java.lang.Object, not a String. In case you want a string representation of whatever object, you have to call the toString() method; this is not the similar as casting the object to a String.

Objects can be converted to a string employing the toString() method:

String myString = myIntegerObject.toString();

There is no such rule about casting. For casting to work, the object should really be of the type you're casting to.

You can't cast apparently anything to a String that isn't a String. You must use either:

"" + myInt;





I prefer the second form, however I think it's personal choice.

Edit OK, here's why I offer the second form. The first form, at the time  compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could say. The second form also has an analogue, Integer.toString(myInt, radix) that lets you seclude whether you want hex, octal, etc. In case you need to be consistent in your code (entirely aesthetically, I guess) the second form can be exercised in more places.

Edit 2 I occupied you intended that your integer was an int and not an Integer. In case it's meanwhile an Integer, only employ toString() on it and be done.

You must call myIntegerObject.toString() in case you want the string representation.

Casting is different than converting in Java, to exercise informal terminology.

Casting an object implies that object meanwhile is what you're casting it to, and you're only saying the compiler about it. For example, in case I have a Foo reference that I know is a FooSubclass example, then (FooSubclass)Foo says the compiler, "don't alter the example, only know that it's really a FooSubclass.

On the other hand, an Integer is not a String, although (as you point out) there are methods for obtaining a String that illustrates an Integer. Because no  instance of Integer can ever be a String, you can't cast Integer to String.

convert it back to the main Integer and cast it to Long

obj.setID(((Integer) row.get("ID")).longValue());
//obj.setID(((Long) row.get("ID")));

Java basic:

Integer num = 1;

Long numInLong = num.longValue();	 // Integer to Long

Long numInLong2 = Long.valueOf(num); // Integer to Long


10 6 4
31,120 points

Related questions

0 votes
1 answer 15 views
Can someone please help me? I would most appreciate it. Thank you very much in advance
asked Jan 23 TeamScript 13.5k points
0 votes
1 answer 11 views
0 votes
2 answers 310 views
Problem : Currently I am working on my app for Android but I am getting following error while working with the SharedPreferences. I am very new to Android App Programming. I am trying to debug it from past 2 days but unable to find the solution ... " android:inputType="number" android:key="capitalownership" android:title="@string/capitalownership" /> Can somebody help me in resolving this error?
asked Feb 17, 2020 mphil 2.3k points
0 votes
1 answer 5 views
Problem: I have the following and I get the error java.lang.String cannot be cast to [Ljava.lang.String; I have changed the Object[] to String[] because I faced the next error: java.lang.Object cannot be cast to [Ljava.lang.String;
asked 3 days ago Ali 4.4k points
0 votes
1 answer 10 views
How it can be possible? Each object can be cast to String, doesn't it?
asked Feb 9 TeamScript 13.5k points
0 votes
1 answer 8 views
Solve this problem, please.
asked Dec 30, 2020 TeamScript 13.5k points
0 votes
1 answer 4 views
Problem: java.lang.classcastexception: java.math.biginteger cannot be cast to java.lang.long I've got List<Long> dynamics. And I want to get max result using Collections. This is my code: List<Long> dynamics=spyPathService.getDynamics(); Long max=((Long)Collections.max(dynamics) ... query.list(); return result; } Now I'm getting java.math.BigInteger cannot be cast to java.lang.Long. What's wrong?
asked 1 day ago Hira 2.2k points
0 votes
1 answer 7 views
Problem: org.json.jsonexception: value <br of type java.lang.string cannot be converted to jsonobject
asked Feb 18 Lucky Guy 1.4k points
0 votes
0 answers 18 views
my program (java) is below. I wrote it with eclipse IDE. I still can&rsquo;t figure out the mistake. package com.in28minutes.firstjavaproject; public class MultiplicationTable { void print() { for (int i = 1; i <= 10; i++) { System. ... public class MultiplicationTableRunner { public static void main(String[] args) { MultiplicationTable instance = new MultiplicationTable(); instance.print(); } }
asked Feb 6 chathura2001 120 points
0 votes
1 answer 444 views
Problem : Currently I am trying to display a JSON content using a API key. But I am unable to get a authentication. I am facing below error in my JsonObject: &ldquo;Org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject&rdquo; In my ... to pass a API key and URL id to get my JSON response in a URL. I display a JSON content using a JSON array.
asked Feb 2, 2020 jwilliam 3.9k points