There are two kind of type conversion in Java:
Implicit type-conversion performed by the compiler automatically; if there will be no loss of precision.
int i = 3;
double f;
f = i;// it is ok, no explicit type casing required.
// here, f = 3.0
The rule is to promote the smaller type to bigger type to prevent loss of precision, known as Widening Conversion (as above example).
newValue = (typecast)value;
double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision (as above example).
Ask Question