Tags

Contextual difference between compound assignment and normal assignment.

var += x;  with respect to

var = var + x;

byte byteVar = 1;
shortshortVar=Short.MAX_VALUE;
System.out.println(byteVar+ " , "+shortVar);
System.out.println("Binary Representation: "+Integer.toBinaryString(byteVar)+" : "+ Integer.toBinaryString(shortVar));
byteVar+=shortVar; //try replacing with other expression
System.out.println("After adding values");
System.out.println(byteVar+ " , "+shortVar);
System.out.println("Binary Representation: "+Integer.toBinaryString(byteVar)+" : "+ Integer.toBinaryString(shortVar));

If you add this statement in place of statement 9 the following error results.

byteVar=byteVar+shortVar;

java.lang.RuntimeException: Uncompilable source code – possible loss of precision

JLS 15.26.2 says

            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.           

byteVar+=shortVar;

is computed as

byteVar=(byte) byteVar+shortVar;

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

The compound assignment operator is simple and use it if operand types are same.

If it deals with different operand types use it with care.

Don’t use it with

operand1+= operand2

if operand2 size is greater than operand1. Eg. Operand1 is byte or short and operand2 is int

operand1 is of type integer and operand2 is of type float,long,double.