ertificación en
AVA
Universidad Nacional de Colombia
Facultad de Ingeniería
Departamento de Sistemas
4. CONVERTING AND CASTING
Objectives
Primitive Conversion
Primitive Casting
Object Reference Conversion
Object Reference Casting
Objectives
Determine the effect upon objects and primitive values of
passing variables into methods and performing assignments
or other modifying operations in that method
Explicit and Implicit Type Changes
You can explicitly change the type of a value by
casting
To cast an expression to a new type, just prefix the
expression with the new type name in parenthesis
Button btn=(Button)(myVector.elementAt( 5 ));
There are situations in which the system implicitly
changes the type of an expression without you
explicitly performing a cast
myVector.addElement( mycolor );
Conversion: automatic non-explicit type change
All conversion rules are enforced at compile time
Most casting and conversion rules accord with
common sense
Primitives and conversion
Both primitive values and object references can be
converted and cast
Four general cases:
Conversion of primitives
Casting of primitives
Conversion of object references
Casting of object references
Primitives and conversion
Three contexts or situations:
Assignment
Method call
Arithmetic promotion
Primitive Conversion: Assignment
happens when you assign a value to a variable of
different type from the original value
int i;
double d;
i=10;
d=i; // assign an int to a double variable
double i;
short s;
d=1.2345;
s=d; // assign a double value to a short
// variable
Error:
“Incompatible type for =.”
Primitive assignment conversion rules
Source type Target type
1. boolean any other OK
2. non-boolean any non-boolean OK
widening conversion
3. non-boolean any non-boolean
narrowing conversion
Widening conversions
Source type Target type
1. byte short, int, long, float, double
2. short int, long, float, double
3. char int, long, float, double
4. int long, float, double
5. long float, double
6. float double
Widening conversion
xxxx ...
...
0 ... 0 xxxx ...
Widening conversions
char
int long float double
byte short
Narrowing conversions
Source type Target type
1. byte char
2. short byte, char
3. char byte, short
4. int byte, short , char
5. long byte, short , char, int
6. float byte, short , char, int, long
7. double byte, short, char, int, long, float
Primitive Conversion: Method call
happens when you pass a value of one type as an
argument to a method that expects a different
type
float frads;
double d;
frads=2.34567f;
d=Math.cos(frads); // pass float to method
// that expects double
double d=12.0;
Object ob=myVector.elementAt(d);
Error:
“Incompatible type for method. Explicit
cast needed to convert double to int”
Widening conversions
SAME AS IN ASSIGNMENT CONVERSIONS!!
char
int long float double
byte short
Narrowing conversions
ARE FORBIDDEN!!
Primitive Conversion: Arithmetic Promotion
happens within arithmetic statements
1. short s=9;
2. int i=10;
3. float f=11.1f;
4. double d=12.2;
5. if (++s*i >= f/d)
6. System.out.println(“>>>>”);
7. else
8. System.out.println(“<<<<”);
values are “promoted” to wider types
Unary operators
Operand Conversion
• byte int
• short int
• char int
otherwise NO CONVERSION
Binary operators
Rule conversion
if one of the operands is
• double then double
else if one of the operands is
• float then float
else if one of the operands is
• long then long
else both operands are converted to
int
Primitives and Casting
Casting: explicitly telling Java to make a conversion
a casting may widen or narrow its argument
To cast, just precede a value with the
parenthesized name of the desired type
int i=5;
double d=(double)i;
int i=5;
double d=i;
same result as above
short s=259;
byte b=s; // compiler error
System.out.println(“s=“+s+”, b= “+b);
Error:
“Explicit cast needed to convert short to byte”
short s=259;
byte b=(byte)s; // Explicit cast
System.out.println(”b= “+b);
0000000100000011
b=(byte)s
00000011
Casting a value to a wider value is always permitted
but never required; if you omit the cast, an
implicit conversion will be performed on your
behalf
1. int i=2;
2. double radians;
. // hundreds of
. // lines of
. // code
600. radians=(double)i;
Explicit casting can make your code more readable
Rules that govern casting of primitive
types
source target
Can any non-boolean any non-boolean
Cannot boolean any other type
Cannot any other type boolean
Object Reference Conversion:
1. Assignment conversion
2. Method-call conversion
3. Casting
Takes place at compile time, this is not the case
for object casting
Object reference assignment
Conversion
Happens when you assign an object reference to a
variable of different type
Classes of object reference type
1. Class type (e.g., Button, FileWriter)
2. Interface type (e.g., Cloneable, LayoutManager)
3. Array type (e.g., int[][], TextArea[])
Oldtype=new Oldtype();
Newtype y=x; // reference assignment
// conversion
Converting Oldtype to Newtype
Oldtype is a Oldtype is an Oldtype is an
class interface array
Newtype is Oldtype must Newtype must Newtype must be
a class be a subclass be Object Object
of Newtype
Newtype is Oldtype must Oldtype must Newtype must be
an interface implement be a Cloneable
interface subinterface of
Newtype Newtype
Newtype is Compiler error Compiler error Oldtype must be an
an array array of some object
reference type that
can be converted to
whatever Newtype
is an array of
Object reference conversion is permitted
when the direction of the conversion is
“up” the inheritance hierarchy
An interface type may only be converted to an
interface type or to Object. If the new type
is an interface, it must be a superinterface
of the old type
A class type may be converted to a class type
or to an interface type. If converting to a
class type, the new type must be a
superclass of the old type. If converting to
an interface type, the old class must
implement the interface
An array may be converted to the class Object,
to the interface Cloneable or Serializable, or
to an array. Only an array of object
reference types may be converted to an
array, and the old element type must be
convertible to the new element type
Object
Fruit
Citrus
(implements
Squeezable)
Lemon Tangelo Grapefruit
Tangelo tange=new Tangelo();
Citrus cit=tange;
This code is fine
Citrus cit= new Citrus();
Tangelo tange=cit;
Compiler Error!!
Grapefruit g=new Grapefruit();
Squeezable squee=g; // No problem
Grapefruit g2=squee; // Error
Fruit fruits[];
Lemon lemons[];
Citrus citruses[]=new Citrus[10];
for (int i=0; i<10; i++) {
citruses[i]=new Citrus();
}
Fruits=citruses; // No problem
lemons=citruses; // Error
Object Method-Call Conversion:
Same as the rules described above for
assignment conversion of objects
• An array may be converted to the class
Object, to the interface Cloneable or
Serializable, or to an array. Only an array of
object reference types may be converted to
an array, and the old element type must be
convertible to the new element type
An interface type may only be converted to an
interface type or to Object. If the new type
is an interface, it must be a superinterface
of the old type
A class type may be converted to a class type
or to an interface type. If converting to a
class type, the new type must be a
superclass of the old type. If converting to
an interface type, the old class must
implement the interface
An array may be converted to the class Object,
to the interface Cloneable or Serializable, or
to an array. Only an array of object
reference types may be converted to an
array, and the old element type must be
convertible to the new element type
Vector myVec=new Vector ();
Tangelo tange=new Tangelo();
myVec.addElement(tange);
Tange will be automatically converted to
type Object
Object Reference Casting:
By using a cast, you convince the compiler to
let you do a conversion that otherwise might
not be allowed
Any kind of conversion that is allowed for
assignments or method calls is allowed for
explicit casting
The power of casting appears when you
explicitly cast to a type that is not allowed by
the rules of implicit conversion
Lemon lem=new Lemon();
Citrus cit=(Citrus)lem;
Legal cast but not needed
Java programs do not deal with objects. They
deal with references to objects.
Color purple=new Color(222, 0, 255)
purple IS NOT an object; it is a REFERENCE TO
an object (the address of the object)
Reference and Object
1011 ... 0110
Object of type Blob
resides in memory at 1011 ... 0110
Object reference variable types can be
1. classes
2. interfaces, or
3. arrays
While an object’s class is unchanging, it may be
referenced by variables of many different
types
Object obj; Vector vec; Stack stk; Serializable s;
1001 ... 0110 1001 ... 0110 1001 ... 0110 1001 ... 0110
Object of type Blob
resides in memory at 1011 ... 0110
The type of reference variable is obvious at
compile time
The class of an object referenced by such a
variable cannot be known until runtime
The rules for casting are broader than for
conversion
Some rules can be enforced at compile time;
other rules can only be enforced during
execution
Possibilities for the old and new type
1. non-final class
2. final class
3. interface
4. array
Compile-time rules
Oldtype is a Oldtype is a Oldtype is an Oldtype is an array
non-final final class interface
class
Newtype Oldtype Oldtype must Always OK Newtype must be
is a non- must extend Object
final class extend Newtype
Newtype or
viceversa
Newtype Newtype Oldtype and Newtype Compiler error
is a final must Newtype must
class extend must be the implement
Oldtype same class interface
Oldtype
Newtype Always OK Oldtype must Almost Newtype must be
is an implement always OK Cloneable
interface interface
Newtype
Newtype Oldtype Compiler Compiler Oldtype must be an
is an must be error error array of some reference
array object type that can be cast to
whatever Newtype is
an array of
Assuming that a desired cast survives
compilation, second check must occur at
runtime
The second check determines whether the two
classes are compatible (i.e., the class can be
converted according to the conversion rules)
Rules of thumb
(compile-time)
When both Oldtype and Newtype are classes,
one class must be a sublcass of the other
When both Oldtype and Newtype are arrays,
both arrays must contain reference types (NOT
PRIMITIVES), and it must be legal to cast an
element of Oldtype to an element of Newtype
You can ALWAYS cast between an interface
and a non-final object
Rules of thumb
(run-time)
If Newtype is a class, the class of the
expression being converted must be Newtype
or must inherit from Newtype
If Newtype is an interface, the class of the
expression being converted must implement
Newtype
Object
Fruit
Citrus
(implements
Squeezable)
Lemon Tangelo Grapefruit
1. Grapefruit g, g1;
2. Citrus c;
3. Tangelo t;
4. g=new Grapefruit(); // class is Grapefruit
5. c=g; // Legal assignment conversion,
6. // no cast needed
7. g1=(Grapefruit)c; // Legal cast
8. t=(Tangelo)c; // Illegal cast
9. // (throws an exception)
1. Grapefruit g, g1;
2. Squeezable s;
3. Tangelo t;
4. g=new Grapefruit();
5. s=g; // Convert Grapefruit to Squeezable
6. // (OK)
7. g1=s; // Convert Squeezable to Grapefruit
8. //(Compiler error)
Implicitly converting an interface to a class is
never allowed; you HAVE to use an explicit cast
7. g1=(Grapefruit)s; // Convert Squeezable to
8. //Grapefruit
1. Grapefruit g[];
2. Squeezable s[];
3. Citrus c[];
4. g=new Grapefruit[500];
5. s=g; // Convert Grapefruit array to
6. // Squeezable array (OK)
7. c=(Citrus[])s; // Cast Squeezable array to
8. // Citrus array (OK)