运算与运算符
运算与运算符
以下是Java中常见的运算符及其示例:
1.算术运算符
加法运算符(+):
int a = 5;
int b = 3;
int c = a + b; // c的值为8
减法运算符(-):
int a = 5;
int b = 3;
int c = a - b; // c的值为2
乘法运算符(*):
int a = 5;
int b = 3;
int c = a * b; // c的值为15
除法运算符(/):
int a = 5;
int b = 3;
int c = a / b; // c的值为1
取模运算符(%):
int a = 5;
int b = 3;
int c = a % b; // c的值为2
2.赋值运算符
等号运算符(=):
int a = 5;
加等于运算符(+=):
int a = 5;
a += 3; // a的值为8
减等于运算符(-=):
int a = 5;
a -= 3; // a的值为2
乘等于运算符(*=):
int a = 5;
a *= 3; // a的值为15
除等于运算符(/=):
int a = 5;
a /= 3; // a的值为1
取模等于运算符(%=):
int a = 5;
a %= 3; // a的值为2
3.比较运算符
大于运算符(>):
int a = 5;
int b = 3;
boolean c = a > b; // c的值为true
小于运算符(<):
int a = 5;
int b = 3;
boolean c = a < b; // c的值为false
大于等于运算符(>=):
int a = 5;
int b = 3;
boolean c = a >= b; // c的值为true
小于等于运算符(<=):
int a = 5;
int b = 3;
boolean c = a <= b; // c的值为false
等于运算符(==):
int a = 5;
int b = 5;
boolean c = a == b; // c的值为true
不等于运算符(!=):
int a = 5;
int b = 3;
boolean c = a != b; // c的值为true
4.逻辑运算符
AND运算符(&&):
int a = 5;
int b = 3;
boolean c = (a > b) && (a < 10); // c的值为true
OR运算符(||):
int a = 5;
int b = 3;
boolean c = (a < b) || (a < 10); // c的值为true
NOT运算符(!):
int a = 5;
boolean c = !(a > 10); // c的值为true
5.位运算符
按位与运算符(&):
int a = 5;
int b = 3;
int c = a & b; // c的值为1
按位或运算符(|):
int a = 5;
int b = 3;
int c = a | b; // c的值为7
按位异或运算符(^):
int a = 5;
int b = 3;
int c = a ^ b; // c的值为6
位移运算符(<<、>>、>>>):
int a = 5;
int b = a << 2; // b的值为20,将a左移两位
int c = a >> 1; // c的值为2,将a右移一位
int d = a >>> 1; // d的值为2,将a无符号右移一位
6.条件运算符
三元运算符(?:):
int a = 5;
int b = 3;
int c = (a > b) ? a : b; // c的值为5,如果a>b,c等于a,否则等于b