![]() |
VOOZH | about |
Java provides primitive data types with fixed memory sizes, and when assigning values between them, compatible types are converted automatically, while incompatible types require explicit casting.
Type conversion in Java is done in two ways:
Widening conversion takes place when two data types are automatically converted. This happens when:
For Example, in java, the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.
Int value 100 Long value 100 Float value 100.0
If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting or narrowing.
char and number are not compatible with each other. Let's see when we try to convert one into another.
Output: An error will be generated
How To Solve The Error:
This error occurs because Java does not allow implicit narrowing conversion from int to char, even if the value can fit. To assign an int to a char, explicit casting is required:
Double value 100.04 Long value 100 Int value 100
Note: While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).
Conversion of int to byte. i = 257 b = 1 Conversion of double to byte. d = 323.142 b= 67
While evaluating expressions, the intermediate value may exceed the range of operands and hence the expression value will be promoted. Some conditions for type promotion are:
result = 626.7784146484375
While evaluating expressions, the result is automatically updated to a larger data type of the operand. But if we store that result in any smaller data type it generates a compile-time error, due to which we need to typecast the result.
100
Note: In case of single operands the result gets converted to int and then it is typecast accordingly, as in the above example.
| Datatype | Bits Acquired In Memory |
|---|---|
| boolean | size - JVM Dependent |
| byte | 8 (1 byte) |
| char | 16 (2 bytes) |
| short | 16(2 bytes) |
| int | 32 (4 bytes) |
| long | 64 (8 bytes) |
| float | 32 (4 bytes) |
| double | 64 (8 bytes) |
The below table demonstrates the key difference between Explicit and Implicit Conversion
Aspect | Implicit Conversion | Explicit Conversion |
|---|---|---|
Syntax | No additional syntax required. | Requires explicit type casting (e.g., (int)). |
Data Compatibility | Only works with compatible types (e.g., numeric). | Works with both compatible and incompatible types. |
Risk of Data Loss | No risk of data loss. | May result in data loss (e.g., truncation). |
Direction | Smaller type to larger type. | Larger type to smaller type. |
Note:
- Use implicit conversion when assigning a smaller data type to a larger one (e.g., int → long).
- Use explicit conversion when assigning a larger data type to a smaller one (e.g., double → int) or for incompatible types.