Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Operators and Assignments - Cast Operator

  • the cast operator (type) is used to convert numeric values from one numeric type to another or to change an object reference to a compatible type
  • used to enable conversions that would normally be disallowed by the compiler
    byte a = 1;
    byte b = 2;
    
    byte c = a + b;         // a and b are promoted to int
    byte c = (byte)(a + b); // compiles ok

Casting with Object references (JLS §5.5, JJ pg 67)

  • a reference of any object can be cast to a reference of type Object
  • a reference to an object can be cast into a reference of type ClassName if the actual class of the object, when it was created, is a subclass of ClassName
  • a reference to an object can be cast into a reference of type InterfaceName if the class of the object implements Interface, if the object is a subinterface of InterfaceName or if the object is an array type and InterfaceName is the Cloneable interface

If you cast up the class hierarchy you do not have to use the cast operator; if you are cast down the class hierarchy you must use the cast operator (BB pg 41)

However, the compiler uses the declared type to verify the correctness of each method call; which means you cannot invoke a subclass method from a superclass reference. (See post by Michael Ernest at JavaRanch)

  • a cast may work at compile-time but fail at runtime if the actual class of the object cannot be converted legally
  • while you can cast up and down the class hierarchy, you cannot cast sideways
  • you can cast an object reference using String
    Example from Java 2 Certification by Jamie Jaworski, pg 69
    
     String s1 = "abc";
     String s2 = "def";
     Vector v  = new Vector();
     v.add(s1);
     s2 = (String) v.elementAt(0); // cast allowed
     System.out.println();
     System.out.println("Value of s2: \t\t" + s2); 
    
     output: abc        
    
    Note: if the String cast is omitted, the type of v.elementAt(0) is an Object and a compile error (incompatible types) results.
  • you cannot use String as a cast type for a primitive type
    String s = (String)x is invalid
    you can use String s = new Byte(x).toString();
X x = new X();
Y y = new Y();      
Z z = new Z();      

X xy = new Y();  // compiles ok (up the hierarchy)
X xz = new Z();  // compiles ok (up the hierarchy) 
Y yz = new Z();  // incompatible type

Y y1 = new X();  // X is not a Y
Z z1 = new X();  // X is not a Z
        
X x1 =  y;       // compiles ok (y is subclass)
X x2 =  z;       // compiles ok (z is subclass)

Y y1 = (Y) x;    // compiles ok but produces runtime error
Z z1 = (Z) x;    // compiles ok but produces runtime error
Y y2 = (Y) x1;   // compiles and runs ok (x1 is type Y)
Z z2 = (Z) x2;   // compiles and runs ok (x2 is type Z)
Y y3 = (Y) z;    // inconvertible types (casts sideways)
Z z3 = (Z) y;    // inconvertible types (casts sideways)

Object o  = z;
Object o1 = (Y)o; // compiles ok but produces runtime error

The casts work at compile time since the cast variable could conceivably be of a compatible type; however, at runtime the type of the variable is known and if it cannot guarantee to implement the contract of the cast type a java.lang.CastClassException will be thrown.

Casting with arrays

  • to cast an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference
double arr[] = {1.5, 2.256, 3.59};
int    arr1[] = (int) arr;    // compile-error

X[] arrX = { new X(), new X(), new X() };
Y[] arrY = { new Y(), new Y(), new Y() };

arrX = arrY;     // compiles ok

Also see:

Example Code

Tips

  • you cannot cast a primitive type to an object reference, or vice versa
  • you cannot cast a boolean type to another primitive type

Traps

  • result of an integer operation on byte or short types being assigned to a byte or short without an explicit cast


Conversions Promotion Overflow Unary Prefix Arithmetic
  Bin/Hex/Octal Bitwise Shift Comparison Logical Assignment
  Cast Ternary String equals() Precedence Bit vs Logic
  Method Invocation