Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have the below piece of code:

Integer mRuntime = (Integer) movie.get("runtime");
String movieRuntime;
if(mRuntime == null){
    movieRuntime="*Not Available*";
} else{
    movieRuntime = String.valueOf(mRuntime);
}

In the above code I am trying to check the value of runtime which is an integer and trying to convert the value to String if it is not NULL. if it is null I am writing a custom message to String telling that it is not available.

But when I try to execute the code I am getting the below message:

nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

at

Integer mRuntime = (Integer) movie.get("runtime");
share|improve this question
    
"I am trying to check the value of runtime which is an integer" based on your error message (Integer) movie.get("runtime") seems to return string, not integer. Double check it. – Pshemo Mar 23 at 20:00
up vote 0 down vote accepted

If the value stored under the key runtime is not of type Integer you will invariably run into this ClassCastException. You can rewrite the thing as follows, assuming movies is a Map:

String movieRuntime;
if (!movies.containsKey("runtime")) {
    movieRuntime="*Not Available*";
} else if (movies.get("runtime") instanceof Integer){
    movieRuntime = String.valueOf(movies.get("runtime"));
}
// add an else case for all the other types
share|improve this answer

movie.get("runtime") returns a String. You want a String. You're good. Just do this:

String movieRuntime = movies.get("runtime");
if (movieRuntime == null) {
    movieRuntime = "*Not Available*";
}
share|improve this answer
2  
Integer.valueOf returns Integer not int so there is no autoboxing here. It is Integer.parseInt which returns int. – Pshemo Mar 23 at 20:06
    
Thank you @Pshemo. That's what I get for typing without compiling. :-) Fixed. – Erick G. Hagstrom Mar 23 at 20:27
1  
In the end, though, he's starting with a String and wants a String, so probably don't need to convert at all. More edits forthcoming. – Erick G. Hagstrom Mar 23 at 20:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.