Java Reference
In-Depth Information
0xff >>> 4 // 11111111 >>> 4 = 00001111 = 15 = 255/16
- 50 >>> 2 // 0xFFFFFFCE >>> 2 = 0x3FFFFFF3 = 1073741811
Assignment Operators
The assignment operators store, or assign, a value into some kind of variable. The
left operand must evaluate to an appropriate local variable, array element, or object
field. The right side can be any value of a type compatible with the variable. An
assignment expression evaluates to the value that is assigned to the variable. More
importantly, however, the expression has the side effect of actually performing the
assignment. Unlike all other binary operators, the assignment operators are right-
associative, which means that the assignments in a=b=c are performed right to left,
as follows: a=(b=c) .
a x
The basic assignment operator is = . Do not confuse it with the equality operator, == .
In order to keep these two operators distinct, we recommend that you read = as “is
assigned the value.”
In addition to this simple assignment operator, Java also defines 11 other operators
that combine assignment with the 5 arithmetic operators and the 6 bitwise and shift
operators. For example, the += operator reads the value of the left variable, adds the
value of the right operand to it, stores the sum back into the left variable as a side
effect, and returns the sum as the value of the expression. Thus, the expression x+=2
is almost the same as x=x+2 . The difference between these two expressions is that
when you use the += operator, the left operand is evaluated only once. This makes a
difference when that operand has a side effect. Consider the following two expres‐
sions, which are not equivalent:
a [ i ++] += 2 ;
a [ i ++] = a [ i ++] + 2 ;
The general form of these combination assignment operators is:
var op = value
This is equivalent (unless there are side effects in var ) to:
var = var op value
The available operators are:
+= -= *= /= %= // Arithmetic operators plus assignment
&= |= ^= // Bitwise operators plus assignment
<<= >>= >>>= // Shift operators plus assignment
The most commonly used operators are += and -= , although &= and |= can also be
useful when working with boolean flags. For example:
i += 2 ; // Increment a loop counter by 2
c -= 5 ; // Decrement a counter by 5
Search WWH ::




Custom Search