Explicit and Implicit Type Changes casting = explicitly changing the value Integer i = (Integer)(myVector.ElementAt(0)) implicit casting( a.k.a. conversion ) myVector.addElement( myColor )
Primitives and Conversion int, float, double, etc Object data types classes you create classes in the JDK
Primitive Conversion: Assignment Rules Boolean cannot be converted to another type non-booleans can be converted to other non-booleans only if they are widening conversions char int long float double byte short
Primitive Conversion: Method Call When you pass a value of one type as an argument to a method that expects a different type public void addFloat( float f ) {…} int i = 2; addFloat( i ); Cannot convert from primitive to Object types int i = 10; myVector.addElement(i) // compiler error - int is not an object
Primitive Conversion: Arithmetic Promotion Unary operator rules byte, short, char, are converted to an int any other type is not converted Binary operator rules if one operand is a double the other is converted to a double elseif one operand is a float the other is converted to a float elseif one operand is a long the other operand is converted to a long else both operands are converted to ints
Primitives and Casting int i = 69 double d = (double) i Booleans cannot be cast to other types and vice versa If you are doing a shortening conversion - data will be dropped page 107 - Figure 4.5
Object Reference and Method Call Conversion Rules An interface type may only be converted to an interface type or Object A class type may be converted to a class type or an interface type( old class must implement the interface ) An array can be converted to: class Object Interface Cloneable to an array Figure 4.7 - page 110
Object Reference Casting: Compile Time When casting from OldType to NewType, one must be a subclass of the other When OldType and NewType are arrays they must be arrays of object references and not primitives and you must be able to cast from OldType to NewType You can always cast from an interface to a non-final object
Object Reference Casting: Run-Time If NewType is a class then the class of the expression being converted must be of NewType or inherit from it If NewType is an interface then the class of the expression being converted must implement it Figure 4.11 116