Witscale Test Center

9.6 Assignment operators


9.6 Assignment operators

You can use assignment operators to store a value of a variable or expression into another variable. Java has two types of assignment operators,

A simple assignment operator =

Several compound assignment operators op= (where op is any of the binary operators * / % + - etc).

It is very common to perform some binary operation and then store its result in the same variable. For example, You can increment a variable as by adding a 1 to it and storing the result back into the same variable. Following code modifies the variable a by incrementing its value and then storing the result back into the variable a.

 

int a = 2;

a = a + 1;

 

The compound assignment operator += provides a shorter version for this operation. Following code also modifies the variable a by incrementing its value and then storing the result back into the variable a.

 

int a = 2;

a += 1;  

     

The expression a += 1 not only increments the variable a but also implicitly casts the incremented value (on right side) before it is assigned to variable on left side. The expression  a+=1 is really equivalent to :

 

a = (int) a + 1;

 

The implicit casting is performed to the type of left-hand variable. Since a is of type int, the value of a+1 is cast to int before assignment. Besides this implicit casting, compound assignment operators work very similar to the assignment operators.