5.5 Type casting 

Previous Index Next 


In Java objects can be type cast. To type cast an object you must specify the type in round brackets before the objects identifier. For instance
z = (Integer)a;
If the cast is illegal the Java VM will throw a ClassCastException. The following code will generate a ClassCastException exception:
Object x = new Integer(0);       // Object is base class of all objects in Java so Integer can be assigned to it
System.out.println( (String)x ); // Illegal cast. Object that x refers to is an Integer not a String
The instanceof operator can be used to test the type of class that an object is. As an Example:
Object x = new Integer(10);

if (  x instanceof Object)
   System.println("It's an Object !");   // All classes descend from Object

if (  x instanceof Number)
   System.println("It's a Number !");   // Number is super class of Integer

if (  x instanceof Integer)
   System.println("It's an Integer !"); // It is an Integer.

if (  x instanceof String)
   System.println("It's a String !");   // It's not a String so this won't print
Produces the following output:
It's an Object !
It's a Number !
It's an Integer !