This tutorial covers only primitive data type casting which explains converting a value of type double to an int or an int to a double. Casting Object / reference variable will be covered in next tutorial.
- Numerical data are called primitive data types
- Objects are called reference data types
The range of numeric / primitive data type increase in following order.
Java allows to perform binary operation on value of mix data type (different data types). Performing binary operations on mix data type, java autometically converts the operand based on the following promotion rules.
- If one of the operand is double, the other is converted into double
- if one of the operand is float, the other is converted into float
- if one of the operand is long, the other is converted into long
- otherwise both operan is converted into int
The resule of 5/2 is 2, because both operands are type of int. The result of 5.0/2 is 2.5, because 5.0 is double and 2 is converted to 2.0.
Let’s consider another example :
If x is a float and y is an int, what will be the data type of the following expression?
Answer is : float
Explicit Type Casting
Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax:
( data type ) expression
(float) x / 5; // type cast x to float, then divide it by 5
(int) (x / y * 5.0) // type cast the result of expression to int
Casting a variable of a type with a large range to a variable of a type with a smaller range is known as narrowing a type.
Consider another example
float f = (float)10.5; //the double value 10.5 is casted into float.
int i = (int)f; //i has a value of 10, the fractional part in f is truncated.
Implicit Type Casting
Casting a variable of a type with a small range to a variable of a type with a larger range is known as widening a type. This type of casting is done autometically.
int i = 10; // i has a value of 10
double d = i; // d has a value of 10.0, int value is implicitly casted to double
Note : Casting does not change the variable being cast. For example, i is not changed after casting in the above code. i has a value of 10 and value in d is 10.0.