赋值运算符
以下是Java语言支持的赋值运算符-
运算符 | 描述 | 例 |
---|---|---|
= | 简单的赋值运算符。将值从右侧操作数分配给左侧操作数。 | C = A + B将A + B的值赋给C |
+ = | 添加AND赋值运算符。它将右操作数添加到左操作数,并将结果分配给左操作数。 | C + = A等于C = C + A |
-= | 减去AND赋值运算符。它从左侧操作数中减去右侧操作数,并将结果分配给左侧操作数。 | C-= A等效于C = C A |
* = | 乘以AND赋值运算符。它将右操作数与左操作数相乘,并将结果分配给左操作数。 | C * = A等于C = C * A |
/ = | 除法和赋值运算符。它将左操作数除以右操作数,并将结果分配给左操作数。 | C / = A等于C = C / A |
%= | 模与赋值运算符。它使用两个操作数取模,并将结果分配给左操作数。 | C%= A等于C = C%A |
<< = | 左移AND赋值运算符。 | C << = 2与C = C << 2相同 |
>> = | 右移和赋值运算符。 | C >> = 2与C = C >> 2相同 |
&= | 按位与赋值运算符。 | C&= 2与C = C&2相同 |
^ = | 按位异或和赋值运算符。 | C ^ = 2与C = C ^ 2相同 |
| = | 按位或(OR)和赋值运算符。 | C | = 2与C = C |相同 2 |
public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c += a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a ; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c /= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c <<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c &= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a ; System.out.println("c |= a = " + c ); } }
这将产生以下结果-
输出结果
c = a + b = 30 c += a = 40 c -= a = 30 c *= a = 300 c /= a = 1 c %= a = 5 c <<= 2 = 20 c >>= 2 = 5 c >>= 2 = 1 c &= a = 0 c ^= a = 10 c |= a = 10