Java's Assignment Operators

The most basic assignment operator is =

However, in Java, any arithmetic or bitwise operator can be joined to = to form a composite assignment operator. For example:

a[func()] += 1; is equivalent to a[func()] = a[func()] + 1;

However, in the first case, func() is called only once. Since it may return a new value when called a second time, we cannot be sure whether or not it is the same array element that is being referred to on both the left and right hand sides of the = sign. The composite += operator is therefore clearer and more predictable in operation when a function is used as an array indexer.

If var is a variable of type Type, then

var op= expr is equivalent to var = (Type)((var) op (expr))

Note that the whole of expr is bound tightly. For example:

a *= b + 1; is equivalent to a = a * (b + 1);
                         not a = a * b + 1;
Although a += 1; is the same as ++a; the ++ is traditionally the preferred coding.
This page's parent within this Web Site. About this Web Site. Its home page. Email its Author.