java入门教程:数据类型_赋值运算符
来源 :中华考试网 2016-04-28
中赋值运算符
赋值就是将数值赋给变量,而这个赋值运算符就充当了这个赋值的任务,其实最简单的赋值运算符,就是“=”。
当然除了“=”外,还有很多其他的赋值运算符。有“+=”、“-=”、“*=”、“/=”、“%=”、“>>=”、“>>>=”、“<<=”、“&=”、“|=”、“^=”。下面有一个简单的例子。
public class data20{ public static void main(String[] args){ int a=5; int b=2; System.out.println("a+=b 的值:"+(a+=b)); System.out.println("a-=b 的值:"+(a-=b)); System.out.println("a*=b 的值:"+(a*=b)); System.out.println("a/=b 的值:"+(a/=b)); System.out.println("a%=b 的值:"+(a%=b)); System.out.println("a>>=b 的值:"+(a>>=b)); System.out.println("a>>>=b 的值:"+(a>>>=b)); System.out.println("a<<=b 的值:"+(a<<=b)); System.out.println("a&=b 的值:"+(a&=b)); System.out.println("a|=b 的值:"+(a|=b)); System.out.println("a^=b 的值:"+(a^=b)); } }
输出结果:
“a+=b”就是 a=a+b=7; “a-=b”就是 a=a-b=7-2=5; “a*=b”就是 a=a*b=5*2=10; “a/=b”就是 a=a/b=10/2=5; “a%=b”就是 a=a%b=5%2=1; “a>>=b”就是 a=a>>b=0; “a>>>=b”就是 a=a>>>b=0; “a<<=b”就是 a=a< “a&=b”就是 a=a&b=0; “a|=b”就是 a=a|b=2; “a^=b”就是 a=a^b=0;
总结:
下面是Java语言支持的赋值运算符:
操作符 | 描述 | 例子 |
---|---|---|
= | 简单的赋值运算符,将右操作数的值赋给左侧操作数 | C = A + B将把A + B得到的值赋给C |
+ = | 加和赋值操作符,它把左操作数和右操作数相加赋值给左操作数 | 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 << = 2等价于C = C << 2 |
>> = | 右移位赋值运算符 | C >> = 2等价于C = C >> 2 |
&= | 按位与赋值运算符 | C&= 2等价于C = C&2 |
^ = | 按位异或赋值操作符 | C ^ = 2等价于C = C ^ 2 |
| = | 按位或赋值操作符 | C | = 2等价于C = C | 2 |
实例
面的简单示例程序演示了赋值运算符。复制并粘贴下面的Java程序并保存为Test.java文件,然后编译并运行这个程序:
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 >>= a = " + c ); c &= a ; System.out.println("c &= 2 = " + 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