Type conversions are the conversion of data types from one form to another. There are several types of conversions which will be seen below,
1. Widening Primitive Conversion: (Implicit Conversion)
Possible only if the
- 2 types are compatible. (eg) double to byte - not possible
- Destination type is larger than the source type.
No automatic type conversion from numeric types to boolean. There are totally 19 widening conversions on primitive types.
- byte to short, int, long, float or double
- short to int, long, float or double
- int to long, float or double
- long to float or double
- float to double
A widening conversion does not lose information.
2. Narrowing Primitive Conversions: (Explicit Conversion)
- Done when automatic type conversion is not possible.
- Uses typecasting.
(eg) int a = 120;
byte b = (byte)a;
System.out.println(b) -> 120
For any value assigned to a byte variable, modulo division by 256 will be done and the resulting remainder will be assigned to the byte variable. Therefore, 120 % 256 =120.
A conversion which occurs when a floating-point value is assigned to an integer type.
(eg) int I = 25.25; i-> 25
byte b = (byte)323.142; -> 67 (because the fractional part is lost and also the value is reduced module 256)
4.Widening and Narrowing Conversion:
byte to char
First, the byte is converted into an int via widening primitive conversion and then the resulting int is converted to a char by narrowing primitive conversion.
(eg) byte b = (byte)130;
char cc = (char)b; -> here 'b' is converted to 'int' by widening conversion; however 'int' has to be converted to 'char' by narrowing conversion.
5. Automatic type expressions:
Sometimes in an expression, the precision required of an intermediate value will exceed the range of either operand.
(eg) byte b=50, a=40, c=100;
int d=a*b/c; //exceeds the range of byte.
For this reason, whenever evaluating an expression, Java automatically promotes each byte, short or char operand to int.
a*b is performed using int and not bytes & hence it is legal.
But these automatic promotions may sometimes cause compile-time errors.
(eg) byte b = 50;
b = b*2; -> error because when the expression is evaluated, the result has already been promoted to int. So, int result cannot be assigned to a byte without typecasting.
byte b = 50;
b = (byte)(b*2);