Type conversion Flashcards
Data Type Conversion
• The process of converting one predefined
data type into another is called Type
Conversion.
• Java facilitates type conversion in 2 forms:
– Implicit Type Conversion (also known as
Promotion or Coercion)
– Explicit Type conversion or Type Casting
Implicit Type conversion
Implicit Type Conversion
• This type of conversion is performed in Java
without the programmer’s intervention.
• It is generally applied in a mixed arithmetic
expression.
• All operands are converted to the largest data
type in the expression, in order to prevent
loss of data.
• It is also known as coercion and promotion.
Explicit Type Conversion
• This is a user-defined conversion that forces an expression to
be of specific type. It is called Type Casting.
• This is normally done when a value of a larger data type is to
be assigned to a smaller data type.
• This is not done implicitly
Potential conversion problems
Type Casting may pose the following problems: – Conversion from float to integer may result in the loss of fractional part(wherein the float is not rounded up).
– In the case of conversion from bigger integer to smaller integer
type, original value may be out of range for target type,
resulting in loss of information.
– In the case of conversion from bigger floating-point type to
smaller floating-point type, there will loss of
precision(significant figures) and original value may be out of
range for target type, thereby resulting in loss of information.
Impossible Conversions
• Any primitive type to a Reference Type or any Reference to a Primitive type • Null value to any primitive type • Any primitive to Boolean • Boolean to any primitive type