四、运算符(operator)
1、算术运算符
+,-,*,/,%,++,–
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
public static void main(String[] args) {
//二元运算符
//1、加减乘除
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b);
System.out.println("============================");
//默认返回int类型,存在long类型则返回long类型
long x = 12312313313123213L;
int y = 123;
short z = 10;
byte f = 8;
System.out.println(a+b+c+d); //Long类型
System.out.println(b+c+d); //Int类型
System.out.println(c+d); //Int类型
System.out.println("============================");
//模运算
int g = 11;
int h = 3;
System.out.println(g%h); //2
System.out.println("============================");
//一元运算符
//++ 自增 --自减
int p = 3;
int o = p++; //执行完这个代码后,先把p赋值给o,再自增
int i = ++p; //执行完这个代码前,先自增 后赋值给p
System.out.println(p); //5
System.out.println(o); //3
System.out.println(i); //5
System.out.println("============================");
//幂运算
//使用math函数
Math.pow(3,2);
}
}
结果:
30
-10
200
0.5
============================
80
70
50
============================
2
============================
5
3
5
============================
2、赋值运算符
=
3、关系运算符
<,>,>=,<=,==,!=,instanceof
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
public static void main(String[] args) {
System.out.println("============================");
//关系运算符 返回 布尔值
int xx = 10;
int yy = 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
}
}
4、逻辑运算符
&&,||,!
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
public static void main(String[] args) {
//逻辑运算符
// 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println(a && b); //false
System.out.println(a || b); //true
System.out.println(!(a && b)); //true
}
}
5、位运算符
&,|,^,~,>>,<<,>>>,!!!
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
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 //取反
<< 左移 // *2
>>右移 // /2
**/
}
}
6、条件运算符
?
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
public static void main(String[] args) {
//三元运算符
//x ? y : z
//如果x == true 则结果为y ,否则为z
}
}
7、扩展运算符
+=,-=,*=,/=
/**
* @Author S1Lu
* @create 2022/10/7 18:54
*/
public class Demo {
public static void main(String[] args) {
int a = 10;
int b = 20;
a += b; //a = a + b
System.out.println(a); //30
a -= b; //a = a - b
System.out.println(a); //10
//字符串连接符 +
System.out.println(""+a+b); //1020 做拼接
System.out.println(a+" "+b); //30 先运算再拼接
System.out.println(a+b+""); //10 20 拼接
}
}