• Register
0 votes
48 views

Problem:

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

2 Answers

–1 vote

Answer:

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

Solution:

Why this is not possible?

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

 Object
     /      \
    /        \
String     Integer

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

 Object
     /
    /
   A
  /
 /
B

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,

Or, 

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;

or:

Integer.toString(myInt);

or:

String.valueOf(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
2 answers 118 views
118 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 mphil 2.3k points
0 votes
1 answer 227 views
227 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: “Org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject” 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 jwilliam 3.9k points
0 votes
1 answer 358 views
358 views
Problem : I am trying to learn Android programming also I am trying to develop a very basic weather app. My code works perfectly if I try to enter any valid city name. But I want to use the toast and it shows me the error and also to the ... .nextCleanInternal(JSONTokener.java:116) at org.json.JSONTokener.nextValue(JSONTokener.java:94) at org.json.JSONObject. How can I fix the above error?
asked Feb 14 mphil 2.3k points
1 vote
1 answer 10 views
10 views
Problem: Hi, I started adopting the Java programming language a few days back. For the time being, I’ve written a java program that should print values from my StudentDatabase using an object of it. Inside my StudentDatabase, I have all the values I need ... I am getting MyProgram.java:4: error: cannot find symbol string name; ^ symbol: class string location: class StudentDatabase 1 error
asked Apr 14 Gavin 15.3k points
1 vote
1 answer 23 views
23 views
Problem: I'm a complete beginner to Java, and after learning some of the basics, I decided to do some practice problems. I am solving problems from many voluntary websites. I've searched for solutions on various forums, but none of them seem to be having the same ... doesn’t run and throws an error. "Variable name" cannot be resolved to a variable. Any Idea? How can I solve the problem?
asked Apr 8 Gavin 15.3k points