The process of converting data types of a value during execution is known as type casting. Type casting can be performed in two ways:
- Implicit type casting
- Explicit type casting
Implicit type casting is performed automatically by the compiler. The variables in an expression must be of same data type. If the data types of operands are different, the value with lower data types is converted into higher data type.
Different types of variables are as follows:
Suppose x is an integer variable and y is a long variable and the following expression is evaluated:
x + y;
In the above expression, data type of x is lower than the data type of y. So the value of x will be converted into long during the evaluation of expression. The data type of x is not changed. Only the data type of the value of x is changed during the evaluation of the expression.
Explicit casting is performed by programmer. It is performed with a cast operator. Cast operator is an operator that tells the computer to convert data type.
The syntax of using cast operator is as follows:
type indicates the data type to which operand is to be converted.
expression indicates the constant, variable or expression whose data type is to be converted.
suppose x and y are two float variables. x contains 10.3 and y contains 5.2 and the following expression is evaluated:
The above expression will generate an error because data type of x and y is float. The modulus operator cannot work with float variables. It only works with integers. So the expression can be written as follows:
(int) x % (int) y
the above statement converts the values of x and y into integers and evaluates the expression. The value of x will be converted to 10 and value of y will be converted to 5. So the result of the above expression will be 0.