Search code examples
javatypescastingoperator-keyword

why does java cant figure out data type of "result2" without type casting it as it figure out datatype of "result1"?


    int result1 = 10;
    result1 -= 5.5;// due to compound assignment this will not cause error and result will be 4
    System.out.println(result1);

    int result2 = 10;
    result2 = (int) (result - 5.5);// this will cause error if we domt use cascting
    System.out.println(result);

what is exact logic behind dynamic datatype conversion for compound assignment operator (" -= ") used in above code. and why does that same logic cannot be applied in case of simple expression.


Solution

  • In Java compound assignment operators: +=, -=, *=, etc., perform an implicit cast to the type of the variable on the left side of the operator.

    This is stated in:

    https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.26.2

    A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

    so:

    result1 -= 5.5
    

    is actually:

    result1 = (int)(result1 - 5.5)
    

    In case:

    result2 = (result2 - 5.5);
    

    there is no implicit cast, so you must do explicit cast with (int)

    As to your question:

    why does that same logic cannot be applied in case of simple expression.

    I suppose in case of compound assignments, language designers decided that such expressions are clear that you want to update the original variable and such implicit cast will make code more concise. But in case of simple expression, such implicit cast might cause data loss - and programmer must be here explicit.