cast : Java Glossary


There are two useful kinds of casts.

  1. Primitive or converting casts e.g.
    // 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: byteint, charint, shortint, intlong, intfloat, intdouble, longdouble. You don’t need an explict cast for longdouble, even though you can sometimes lose some low order bits of precision.
  2. Mollifying casts assure Java that a general reference is actually something more specific, a
    // 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.

Casts in C/C++ will let you overlay four bytes on an int or two shorts on an int. There is absolutely no way to do that in Java. Because Java is WORA (Write Once, Run Anywhere), the design of Java and the JVM prevents you from writing code that would behave differently on a big-endian vs little-endian hardware on on a hardware that had 36 bit registers with 9 bit bytes.

Learning More

Oracle’s Javadoc on Class.isAssignableFrom : available:
Oracle’s Javadoc on Class.asSubclass : available:

available on the web at:
ClustrMaps is down

optional Replicator mirror
on local hard disk J:

Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy.
Your face IP:[]
You are visitor number 42,158.