1. The process of converting one data type to another is called casting or type casting.
2. If the two types are compatible, then java will perform the conversion automatically.
3. It is possible to assign an int value to long variable.
4. However, if the two types of variables are not compatible, the type conversions are not implicitly allowed, hence the need for type casting.
There are two types of conversion:
1.Implicit type-casting:
2.Explicit type-casting:
1. Implicit type-casting:
Implicit type-casting performed by the compiler automatically; if there will be no loss of precision.
Example:
int i = 3;
double f;
f = i;
output:
f = 3.0
Widening Conversion:
The rule is to promote the smaller type to bigger type to prevent loss of precision, known as Widening Conversion.
2. Explicit type-casting:
• Explicit type-casting performed via a type-casting operator in the prefix form of (new-type) operand.
• Type-casting forces an explicit conversion of type of a value. Type casting is an operation which takes one operand, operates on it and returns an equivalent value in the specified type.
Syntax:
newValue = (typecast)value;
Example:
double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision.