The above code snippet produces an output which I thought would throw an error. My understanding on the assignment operator was it will behave like val = val + x so val would also type cast to int and addition would be performed resulting in int value. So, when it tries to assign that to a short value it would throw an error.
Could anyone please explain how this works internally in java?
With an “operator followed by assignment” operator, the compiler throws in an implicit cast of the RHS value to the LHS type. (You can sort of reason why why it should or why it should not be that way, but the bottom line is, as usual, “thems are the specs.”)
Yes, the details are in the link I posted earlier (No 2). It means the variable on the left retains its type and allows a += or -= or something= expression always to compile without needing a cast. It also means you can get confusion if you start mixing types:-The example in the link I posted shows similar potential for confusion, by adding 4.6.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop