Java Type Casting is a way to convert one data type to another data type. Type casting in Java is broadly classified into two categories:
- Widening or Automatic Type Conversion
- Narrowing or Explicit Type Conversion
Widening or Automatic Type Conversion
This type of type casting is also called automatic type conversion. In this type of conversion, Java automatically converts a smaller data type into a larger data type. The reason it’s called a “widening” conversion is because the size of the data type is getting larger.
int myInt = 100; long myLong = myInt;
In this example, the int value 100 is automatically converted to a long value, which is a larger data type.
Narrowing or Explicit Type Conversion
Narrowing or explicit type conversion is the process of converting a data type with a wider range of values to a data type with a narrower range of values. It is also known as downcasting.
Narrowing or explicit type conversion is required when we need to store a value of a wider data type into a variable of a narrower data type. For example, we may need to convert a double value to an int value. In this case, we use explicit type conversion to perform the conversion.
The syntax for explicit type conversion is as follows:
narrowed_data_type variable_name = (narrowed_data_type) value_to_be_converted;
Here, the value to be converted is the variable or expression whose data type needs to be narrowed. The narrowed_data_type is the data type into which we want to convert the value.
For example, let’s say we have a double value
d and we want to store it in an int variable
i. We can use explicit type conversion as follows:
double d = 3.14; int i = (int) d;
Here, the value of
d is explicitly converted to an int value using
(int) before it. The value of
i will be
3, which is the integer value of
It is important to note that when narrowing the data type, we may lose some information, such as decimal points or significant digits. Therefore, we should use narrowing type conversion carefully and only when necessary.