Index
Type Casting
The process of converting the value of one data type (int
, float
, double
, etc.) to another data type is known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus on the major 2 types.
To learn about other types of type conversion, visit Java Type Conversion (official Java documentation).
Explicit conversion
Using a method that takes an argument of one type and returns a value of another type
Some of this methods are:
Integer.parseInt()
Double.parseDouble()
Integer.toString()
Math.round()
Math.floor()
Math.ceil()
Implicit Type Casting
Java automatically converts one data type to another data type.
Converting int to double
Here, the Java first converts the int
type data into the double
type. And then assign it to the double
variable.
Tip
In the case of Implicit Type Casting, the lower data type (having smaller size) is converted into the higher data type (having larger size). Hence there is no loss in data. This is why this type of conversion happens automatically.
Explicit Type Casting
In Explicit Type Casting, we manually convert one data type into another using the parenthesis.
Example: Converting double into an int
In the above example, we are assigning the double
type variable named num to an int
type variable named data.
Notice the line,
int data = (int)num;
Here, the int
keyword inside the parenthesis indicates that that the num variable is converted into the int
type.
In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically.
Examples
Expressions | Type | Value |
---|---|---|
(int)2.71828 | int | 2 |
Math.round(2.71828) | long | 2 |
(int)Math.round(2.71828) | int | 2 |
(int)Math.round(3.14159) | int | 3 |
Integer.parseInt("42") | int | 42 |
"42" + 99 | String | “4299” |
42 * 0.4 | double | 16.8 |
(int)42 * 0.4 | double | 16.8 |
42 * (int)0.4 | int | 0 |
(int)(42 * 0.4) | int | 16 |