Introduction
- In Java, casting is used to convert one data type to another data type.
- In Java, casting can be done manually or it can happen automatically.
Automatic casting (Widening conversion)
- In Java, compatible data types will be automatically converted when one type of data assigned to another type. (Without special notation.)
- To this to happen, following conditions need to be satisfied.
- The two types need to be compatible.
- The destination type should be larger than the source type in size.
- When considering the data type compatibility in widening conversion,
- Integers or floating point values cannot be automatically casted to string or vice versa.
- And floating point values cannot be automatically casted to integers.
- But integers can be automatically casted to floating point data types.
- Also numeric types cannot be automatically casted to char or boolean or vice versa.
- If automatic casting (Widening conversion) is not compatible, then the data types need to be explicitly converted to the desired data type with the proper syntax.
- Now let’s explore the casting process in Java. 🚀
An int value can be automatically assigned into a byte variable.