运算符类型
- 算数运算符:+,-,*,/,%(模运算[取余操作]),++,--
public class Demo01 {
public static void main(String[] args) {
// 二元运算符
int a = 10;
int b = 20;
int c = 10;
int d = 10;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b); // 在除出来小数的时候,提前转换类型
long a1 = 123123123123123L;
int b1 = 123;
short c1 = 10;
byte d1 = 8;
System.out.println(a+b+c+d); // Long。当变量中有一个long类型时,计算结果为long类型
System.out.println(b+c+d); // Int
System.out.println(a); // Int
// 取余,模运算
int a3 = 10;
System.out.println(a%3); // 结果为:1
// 自增、自减
int a4 = 3;
int b4 = a++; // 等价于a = a+1,执行这行代码时,先给b赋值,然后再自增
System.out.println(a); // 4 这里输出时,a已经完成了自增操作,所以为4
int c4 = ++a; // 先自增,再赋值给b
System.out.println(a4); // 5
System.out.println(b4); // 3
System.out.println(c4); // 5
}
}
public class Demo01 {
public static void main(String[] args) {
int a = 3; // 把3赋值给a
}
}
- 关系运算符:>, <, <=, >=, ==, !=, instanceof
public class Demo01 {
public static void main(String[] args) {
// 关系运算符返回结果:布尔值 true false
int a = 10;
int b = 20;
System.out.println(a>b); // false
System.out.println(a<b); // true
System.out.println(a==b); // false
System.out.println(a!=b); // true
}
}
public class Demo01 {
public static void main(String[] args) {
// 与、或、非
boolean a = true;
boolean b = false;
System.out.println("a && b:" + (a&&b)); // 逻辑与:两个都为真,结果为true
System.out.println("a || b:" + (a||b)); // 逻辑或:有一个为真,结果为true
System.out.println("!(a&&b):" + !(a&&b)); // 结果为真,则为假,结果为假,则为真
// 短路运算
int c = 5;
boolean d = (c<4)&&(c++<4); // 因为c<4为假,所以&&后边的语句不为执行,c不会执行++操作,所以d的结果为假,而c的值不变
System.out.println(d); // false
System.out.println(c); // 5
}
}
- 位运算符:&, |, ^, ~, >>, <<, >>>
public class Demo01 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
A&B 0000 1100 按位与:每一位上,都为1,则为1
A|B 0011 1101 按位或:每一位上,有一个为1,则为1
A^B 0011 0001 异或:每一位上,相同为0,不相同为1
~B 1111 0010 每一位上,1为0,0为1
<< 2<<3=16 左移,左移相当于把数字*2
>> 右移,相当于把数字/2
原理:进行二进制运算
0000 0001 1
0000 1000 8
*/
}
}
public class Demo01{
public static void main(String[] args){
// 三元运算符 ?:
// x ? y : z:如果为true,则结果为y,否则结果为z
int score = 50;
String type = socre < 60? "不及格": "及格";
System.out.println(type)
}
}
public class Demo01 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; // 等价于:a=a+b
a-=b; // 等价于:a=a-b
// 字符串连接
System.out.println(""+a+b); // 1020,当+号左边出现字符串的时候会拼接
System.out.println(a+b+""); // 30,当+号邮编出现字符串的时候,左边的会计算
System.out.println(a+b+""+a); // 133,字符串左边先计算,再和边拼接
}
}