About Lesson
In Java, type conversion is the process of converting a value of one data type to another. Sometimes, it’s necessary to convert a value to a different data type to perform a specific operation. There are two types of type conversions in Java: implicit and explicit.
- Implicit type conversion (widening): This happens automatically when a value of a smaller data type is assigned to a variable of a larger data type. For example, when an integer value is assigned to a float variable, the integer value is automatically converted to a float.
java
int i = 10;
float f = i; // Implicit type conversion from int to float
- Explicit type conversion (narrowing): This requires the use of a casting operator to convert a value of a larger data type to a smaller data type. For example, when a float value is assigned to an integer variable, the float value must be explicitly converted to an integer using the casting operator.
java
float f = 3.14f;
int i = (int) f; // Explicit type conversion from float to int using casting
Casting is the process of converting a value of one data type to another. It’s used in explicit type conversion to convert a value of a larger data type to a smaller data type or vice versa. There are two types of casting in Java: widening and narrowing.
- Widening Casting: This happens automatically when a value of a smaller data type is assigned to a variable of a larger data type. This is the same as implicit type conversion.
java
int i = 10;
float f = i; // Widening casting from int to float
- Narrowing Casting: This requires the use of a casting operator to convert a value of a larger data type to a smaller data type. This is the same as explicit type conversion.
java
float f = 3.14f;
int i = (int) f; // Narrowing casting from float to int using casting