Converting Between Integer Types
In Java, you can convert between different integer data types using explicit type casting or automatic type promotion.
Explicit Type Casting
Explicit type casting is used when you want to convert a larger integer type to a smaller one. This can result in data loss if the value is outside the range of the target data type.
int intValue = 1000;
byte byteValue = (byte) intValue; // Explicit cast from int to byte
In the example above, the int
value 1000
is converted to a byte
value, which will result in a value of -24
due to the limited range of the byte
data type.
When performing arithmetic operations or assigning a value to a variable, Java will automatically promote the operands to a larger data type to prevent data loss.
byte byteValue = 42;
short shortValue = 12345;
int intValue = byteValue + shortValue; // Automatic promotion to int
In the example above, the byte
and short
values are automatically promoted to int
when performing the addition operation.
The following table shows the automatic type promotion rules in Java:
Operation |
Promotion Rule |
byte and short |
Promoted to int |
int and long |
Promoted to long |
long and float |
Promoted to float |
float and double |
Promoted to double |
By understanding the concepts of explicit type casting and automatic type promotion, you can effectively manage the conversion between integer data types in Java.