I’m currently tutoring a high school student in AP Java and she asked me a question about “double casting”. I did not ever hear of this term before, but apparently her teacher expects her to know it for their upcoming final.
The example her teacher provided was if you wanted to cast an Integer into a String, you would have to do the following to not get a compiler error:
Integer i = new Integer(5);
String s = (String)(Object) i;
The question is: when would you want to do this in real life?
The teacher only provided examples which result in a run time error. Also, I never really knew there was a term for this, but it just seems like a bad idea to do it because there’s only an error when the two types are incompatible.
Thanks!
Yeah, I’m pretty sure that’s not a thing. There’s no reason that double casting would ever be necessary – it’s possible it might get rid of a compile warning about unsafe casting (in which case you’re probably doing it wrong), but otherwise that’s just not right.
I mean, there’s auto
toStringcalling e.g.println("" + i), but even then you don’t need to cast to an object first…Edit: After reading Tom’s answer I’m suddenly unsure about this answer – primitives and (particularly) generics can actually use this. I don’t have the ability to test anything right now, but anyone reading this answer should definitely take a look at his (and probably upvote it).
I’m going to stick to the line that there are no (or at least extremely few and far between) good reasons to do this, however, and the provided example certainly has nothing to do with it.