import java.util.Vector;   // req'd for Java 2 Certification example

class TestCast {

    public static void main(String[] args) {

    /** Casting Primitive Types ***************************************/    
        byte a = 1;
        byte b = 2;
        byte c;
        
        double d = 199.99;
        
    //  c = a + b;         // compile-error: possible loss of precision
        c = (byte)(a + b); // compiles ok; need to cast the expression
                           //   or both a and b individually
    //  c = d;             // compile error                   
        c = (byte) d;      // compiles ok

        
    //  String s = (String) b;      // compile-error
        String s = new Byte(b).toString();
                                

    /** Casting arrays *********************************************/
        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;
    
    
    /** Casting classes *********************************************/
    
        X x = new X();
        Y y = new Y();
        Z z = new Z();
        
        X xy = new Y();     // compiles ok
        X xz = new Z();     // compiles ok
//      Y yz = new Z();     // compile-error: Z is not a Y
        
//      Y y1 = new X();     // compile-error: X is not a Y
//      Z z1 = new X();     // compile-error: X is not a Z
        
        X x1 =  y;          // compiles ok (Y is subclass of X)
        X x2 =  z;          // compiles ok (Z is subclass of X)                                
        
//      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
        Z z2 = (Z) x2;      // compiles and runs ok
//      Y y3 = (Y) z;       // compile-error: inconvertible types
//      Z z3 = (Z) y;       // compile-error: inconvertible types

        Object o  = z;
//      Object o1 = (Y)o;   // compiles ok but produces runtime error
        
        /** Example from Java 2 Certification by Jamie Jaworski
         *************************************************/
         
         String s1 = "abc";
         String s2 = "def";
         Vector v  = new Vector();
         v.add(s1);
         s2 = (String)v.elementAt(0);
         System.out.println();
         System.out.println("Value of s2: \t\t" + s2);
        
  }

}

class X {}
class Y extends X {}
class Z extends X {}
