Page 111 - computer science (868) class 11
P. 111
5.5 TYPE CONVERSION
The process of changing the value of one type to another type is known as type conversion. It is also known as type
casting. It is required in situations when a method or an expression returns one type of value and it is stored in a
variable of a different data type. For example,
import java.util.*;
class average
{
public static void main()
{
Scanner sc = new Scanner(System.in);
double a,b,c;
int avg;
System.out.println("Enter two numbers:");
a = sc.nextInt();
b = sc.nextInt();
c = a+b;
avg = (int)c;
System.out.println("Average : "+avg);
}
}
Here, “a” and “b” are variables of double data type and they are converted to int data type and stored in the “avg”
variable.
The casting is performed by keeping the target data type in parentheses to the left of the value which is being converted.
Syntax of conversion:
Datatype variable = (datatype)variable_to_be_converted;
There are two types of conversions in Java, which are as follows:
• Implicit Type Conversion
• Explicit Type Conversion
5.5.1 Implicit Type Conversion
Implicit type conversion takes place when the target data type is larger than the source type, i.e., when we assign the
value of a smaller data type to a larger data type.
byte
short
char int float
long double
In implicit type conversion, the resultant data types are automatically chosen by the compiler. It is a process of widening.
109
Primitive Values, Wrapper Classes, Types and Casting 109

