一、二元运算符:
public class Demo01 {
public static void main(String[] args) {
//Ctrl + D :复制当前行到下一行
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); //强转为小数否则输出为0
}
}
public class Demo02 {
public static void main(String[] args) {
long a = 12121212121L;
int b = 123;
short c = 10;
byte d = 8;
System.out.println(a+b+c+d); //结果:12121212262为Long类型
System.out.println(b+c+d); //Int
System.out.println(c+d); //Int
//如果运算中有Long或Double结果为Long 或 Double
//如果运算中没有如上则结果为Int
//cast 转换
}
}
二、关系运算符:
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回结果:True / False 布尔值
int a =10;
int b =20;
int c =21;
System.out.println(a>b); //false
System.out.println(a<b); //true
System.out.println(a==b); //false
System.out.println(c%a); //取余为1
System.out.println(a!=b); //true
}
}
三、一元运算符:
public class Demo04 {
public static void main(String[] args) {
//++ -- 自增 自减 一元运算符
int a = 3;
int b =a++; //执行完这行代码后,先给b赋值,再自增
//a = a+1;
System.out.println(a); //结果为:4
int c =++a; //执行完这行代码前,先自增,再给c赋值
System.out.println(a);//结果为:5
System.out.println(b);//结果为:3
System.out.println(c);//结果为:5
//幂运算 2^3 很多运算会使用一些工具类来操作
double pow = Math.pow(2,3);
System.out.println(pow); //结果为:8.0
}
}
四、逻辑运算符:
public class Demo05 {
public static void main(String[] args) {
// 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b)); //false逻辑与运算: 两个都为真则为真
System.out.println("a || b:"+(a||b)); //true逻辑或运算: 两个有一个为真则为真
System.out.println("-(a && b:)"+!(a&&b)); //如果是真则变为假
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);
System.out.println(d); //false
System.out.println(c); //5 因为判断c<4为假后,不再执行后面的c++
}
}
五、位运算:
public class Demo06 {
public static void main(String[] args) {
/* A = 0011 1100
B = 0000 1101
A&B 与 0000 1100
A|B 或 0011 1101
A^B 异或 0011 0001 (相同为0不同为1)
~B 取反 1111 0010
<< 左移
>> 右移
*/
//拓展:位运算:左移(乘于2) 右移(除于2)
System.out.println(2<<3); //相当于2*8为16
}
}
六、三元运算符:
public class Demo08 {
public static void main(String[] args) {
// x ? y : z 意为:如果x==true,则结果为y,否则为z
int score = 50;
String type = score < 60 ? "不及格":"及格"; //必须掌握
System.out.println(type); //不及格
}
}
七、拓展:
public class Demo07 {
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); //10
//拓展:字符串连接符 + , String
System.out.println(""+a+b); //1022 字符串在前面,则要进行拼接
System.out.println(a+b+""); //30 字符串在后面,则先运算
}
}