Page 148 - Computer science 868 Class 12
P. 148
5.3 TYPE CASTING
Type Casting or Type Conversion is a process of converting one data type value into another data type value in Java.
It is required in situations when a method or an expression returns one type of value and is stored in a variable of a
different data type.
For example:
int number = 5;
double decimal = (double)number;
Syntax:
Datatype variable = (datatype)variable_to_be_converted;
There are two types of conversions in Java. They are:
• Implicit Conversion
• Explicit Conversion
5.3.1 Implicit Conversion
The implicit conversion is done automatically. It takes place when the two data types are compatible. The target type
is larger than the source type, i.e., when we assign the value of a smaller data type to a larger data type.
In implicit type conversion, the data type of a variable is automatically converted into a higher type without any extra
coding. This conversion is done by the system itself and no part of the data value is lost. The resultant data types are
not specified and are chosen by the compiler. This process of converting a lower data type into a higher data type is
known as widening. It is also known as coercion.
The order of lower data type to a higher data type is as follows:
byte short char int long float double
In the above order, the left-side data type is converted into the right-side data type in the implicit conversion.
Let us take an example for better understanding.
int a = 6;
double b = 4.5, c;
c = a+b;
System.out.println(c);
Output: 10.5
The mechanism of implicit conversion in the above example is as follows:
c = a + b ;
Here, the larger data type
is double, so after addition,
double the result is converted into
int double type without any
loss of value.
double
5.3.2 Explicit Conversion
In explicit conversion, a value of a larger data type is converted into a lower data type but only with the help of user’s
intervention. This process of converting a lower data type into a higher data type is called narrowing. It is mainly used
for incompatible data types where automatic conversion is not possible. It requires the user’s intervention. Here, we
must mention the desired data type for the required conversion.
146146 Touchpad Computer Science-XII

