There are two useful kinds of casts.
// primitive converting cast short s = (short) someInt;would convert to a short integer. Converting casts come is two flavours narrowing and widening. Narrowing casts such as (int) someLong generally reduce the number of bits in the representation. They are mandatory. Widening casts such as (long) someInt generally increase the number of bits in the representation. They are optional. Casts you can leave out include: byte → int, char → int, short → int, int → long, int → float, int → double, long → double. You don’t need an explict cast for long → double, even though you can sometimes lose some low order bits of precision.
// mollifying cast Dalmatian d = (Dalmatian) dog;
assures Java that the dogRef pointer really points to a Dalmatian. Java checks that this is indeed so before proceeding. If it is not a Dalmatian (or subclass of Dalmatian) as you claimed, it throws a CastClassException. It has no way to fix the problem by somehow converting the Object to a Dalmatian.
Casting objects is a misleading terminology. Any actual object has a definite class, set when it was instantiated. Nothing can change that during the lifetime of the object. The object it self is unchanged when you cast its reference.
In the days before generics, casts were most needed after you retrieved an element from a Collection. The Collection just gave you a generic Object, but you knew better what it was, since you knew what sort of Objects you put into the collection. Now the explicit casts are no longer needed. Javac.exe transparently inserts any needed checkcast JVM (Java Virtual Machine) instructions in the generated code.If a mollifying downcast fails, because the object is not really what you tried to cast it to, you will get a ClassCastException. Upcasts always succeed. Upcasts are always unnecessay.
Before you cast, you can use instanceof, or one of its brothers, to check if a cast will work.
available on the web at:
optional Replicator mirror
Please email your feedback for publication, letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : . If you want your message, your name or email kept confidential, not considered for public posting, please explicitly specify that. Unless you state otherwise, I will treat your message as a letter to the editor that I may or may not publish in the feedback section. After that, it will be too late to retract it. If you disagree with something I said, especially when sending an ad-hominem attack, a rant composed mainly of obscenities or a death threat, please quote the offending passage and cite the web page where you found it, tell me why you think it is wrong, and, if possible, provide some supporting evidence. I can’t very well fix erroneous or ambiguous text if I can’t find it.
Your face IP:[188.8.131.52]
|Feedback||You are visitor number 42,053.|