Java赋值运算符实例讲解
内容摘要
赋值运算符左面的操作数必须是变量,不能是常量或表达式,赋值表达式的值就是=左面变量的值。
文章正文
赋值运算符左面的操作数必须是变量,不能是常量或表达式,赋值表达式的值就是=左面变量的值。
注意:
1)不要将赋值运算符=与关系运算符==混淆。
2)除赋值运算符=外,还有扩展赋值运算符。
赋值运算符 | 说明 | 举例 |
= | 将右操作数的值赋给左操作数 | c=a+b |
+= | 将左操作数和右操作数相加的值赋给左操作数 | c+=a等价于c=c+a |
-= | 将左操作数和右操作数相减的值赋给左操作数 | c-=a等价于c=c-a |
*= | 将左操作数和右操作数相乘的值赋给左操作数 | c*=a等价于c=c*a |
/= | 将左操作数和右操作数相除的值赋给左操作数 | c/=a等价于c=c/a |
%= | 将左操作数和右操作数取余后的值赋给左操作数 | c%=a等价于c=c%a |
&= | 按位与赋值运算符 | c&=1等价于c=c&1 |
|= | 按位或赋值运算符 | c|=1等价于c=c|1 |
^= | 按位异或赋值运算符 | c^=1等价于c=c^1 |
>>= | 按位右移赋值运算符 | c>>=1等价于c=c>>1 |
<<= | 按位左移赋值运算符 | c<<=1等价于c=c<<1 |
实例:
public class Main { public static void main(String[] args) { int a = 1; int b = 2; 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 = 3; c = 4; c /= a ; System.out.println("c /= a = " + c ); a = 5; c = 6; 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 ; System.out.println("c ^= a = " + c ); c >>= 1 ; System.out.println("c >>= 1 = " + c ); c <<= 1 ; System.out.println("c <<= 1 = " + c ); } }
运行结果如下:
c = a + b = 3 c += a = 4 c -= a = 3 c *= a = 3 c /= a = 1 c %= a = 1 c &= a = 1 c |= a = 5 c ^= a = 0 c >>= 1 = 0 c <<= 1 = 0
代码注释
[!--zhushi--]