
1. Data Conversion
•In Java, data conversions can occur in three ways:
–assignment conversion
float f;
int i = 5;
f = i; // f is 5.0
–promotion
float f = 2.0f;
// or 2.0F since 2.0 is a double constant
// float f = 2.0; wrong!
int i = 5;
f = f/i;
// the value of i is promoted to float type and //
then the division between two float type data //is
performed
–casting
float f = 2.0f;
int i = 5;
i = (float)f/i;
//since the expression of “f/i” will return a
//float type data which could not be
//automatically converted to integer and
casting //is required
//Casting: a pair of parenthesis with casting
//type enclosed such as (int) (float)
•Widening conversions: from small data type to a larger one
short -> int -> long
float -> double
int -> float
long -> double
Reverse arrows correspond to narrowing conversions
Widening conversions are safe and could be done automatically.
int i = 5;
float f;
f = i; // int -> float
Narrowing conversions need to be done through casting!
i = f; // wrong assignment. Correct one is: i = (float)f and the value of i is the
integer part of variable f.
Try to understand:
int total = 20, count = 7; float average;
average = total / count; // 2.0
average = (float)total / count; // 2.857143
average = total / (float)count; // 2.857143