Type conversion in Java, also known as type casting, is the process of converting a value of one data type to another data type.
There are two types of type conversions in Java:
- Implicit Conversion
- Explicit Conversion
Implicit Type Conversion
In implicit type conversion, the conversion is done automatically by the compiler. This occurs when a value of a smaller data type is assigned to a variable of a larger data type, or when a value of a data type with less precision is assigned to a variable of a data type with greater precision. For example:
int num1 = 10;
double num2 = num1; // implicit conversion from int to double
In this example, the value of the integer variable
num1 is assigned to the double variable
num2. Since a double has more precision than an int, the compiler automatically converts the int value to a double value.
Explicit Type Conversion
In explicit type conversion, the conversion is done manually by the programmer using casting. This occurs when a value of a larger data type is assigned to a variable of a smaller data type, or when a value of a data type with more precision is assigned to a variable of a data type with less precision. For example:
double num1 = 10.5;
int num2 = (int) num1; // explicit conversion from double to int
In this example, the double value
num1 is cast to an int value using the
(int) operator. Since an int has less precision than a double, the decimal portion of the double value is truncated when it is cast to an int.
It is important to note that some types of conversions may result in data loss or unexpected behavior. For example, converting a floating-point number to an integer type may result in the loss of the fractional part of the number. Therefore, it is important to use type conversion carefully and only when necessary.