Pages

Java - Arithmetic compound assignment operators performing implicit type cast and automatic type conversion

The arithmetic compound assignment operators implicitly perform both automatic type conversion (widening conversion) and type casts the result of the arithmetic operation to the data type of destination variable.

The arithmetic compound assignment operators are given below

Operator
Explanation
+=
Addition assignment
-=
Subtraction assignment
*=
Multiplication assignment
/=
Division assignment
%=
Modulus assignment

The below example illustrates how automatic type conversion and implicit type cast is performed.


class Test {
       public static void main(String arg[]) {
              byte byteVar = 100;
              int intVar = 110;
              float floatVar = 1.2F;
              double doubleVar = 1.3D;

              byteVar *= doubleVar;          //Expression 1  
              byteVar = byteVar * doubleVar; // results in compilation error "Type mismatch: cannot convert from double to byte"
             
              intVar *= floatVar;            //Expression 2
              intVar = intVar * floatVar;    // results in compilation error "Type mismatch: cannot convert from float to int"
       }
}

 Explanation for Expression 1: (byteVar *= doubleVar)

Ø  Java compiler initially expands this expression into byteVar = byteVar * doubleVar

Ø  Then it type casts byteVar to double. So the expression becomes byteVar = (double)byteVar * doubleVar

Ø  Then it type casts whole right hand side expression to byte. So, the expression byteVar *= doubleVar finally internally converted into byteVar = (byte)((double)byteVar * doubleVar)

If we explicitly code “byteVar = byteVar * doubleVar” then compiler would throw "Type mismatch: cannot convert from double to byte" error. To avoid the compilation error we need to explicitly type cast the both byteVar and entire right hand side expression as shown above.

Explanation for Expression 2: (intVar *= floatVar)

Ø  Java compiler initially expands this expression into intVar = intVar * floatVar

Ø  Then it type casts intVar to float. So the expression becomes intVar = (float)intVar * floatVar

Ø  Then it type casts whole right hand side expression to int. So, the expression intVar *= floatVar finally internally converted into intVar = (int)((float)intVar * floatVar)

If we explicitly code “intVar = intVar * floatVar” then compiler would throw "Type mismatch: cannot convert from float to int". To avoid the compilation error we need to explicitly type cast the both intVar and entire right hand side expression as shown above.

No comments :

Post a Comment