Download presentation
Presentation is loading. Please wait.
1
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 )
2
Primitives and Conversion
int, float, double, etc Object data types classes you create classes in the JDK
3
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
4
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
5
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
6
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 Figure 4.5
7
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 page 110
8
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
9
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.