基本运算符
Java支持如下格式的运算符 优先级: 一般使用括号,表示得更清楚
- 算术运算符: +(加)、—(减)、*(乘)、/(除)、%(口语余数,属于模运算)、++、——;
public class Demo01 {
public static void main(String[] args) {
//二元运算符
//ctrl + d :复制当前行到下一行
int a = 10;
int b = 20;
int c = 30;
int d = 40;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b); //输出结果为0,显然是错误的,因为int类型取整,所以导致结果为0.故强转类型,可正确显示结果
System.out.println(a/(double)b); //输出结果为0.5,符合预期
}
}
public class Demo04 {
public static void main(String[] args) {
int a = 3;
int b = a++;
int c = ++a;
System.out.println(a);
System.out.println(b);
System.out.println(c);
double pow = Math.pow(2, 3);
System.out.println(pow);
}
}
public class Demo03 {
public static void main(String[] args) {
//关系运算符的返回结果;正确 错误 布尔值
//配合if 使用
int a = 10;
int b = 20;
int c = 21;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
System.out.println(c%a); //模运算(取余数) 21/10=2.....1;因此结果输出为1
}
}
public class Demo05 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b:"+ (a && b));
System.out.println("a || b"+ (a || b));
System.out.println("! (a && b):"+ !(a && b));
System.out.println("=========================================");
int c = 5;
boolean d = (c<4)&&(c++<7);
System.out.println(c);
System.out.println(d);
System.out.println("===============================================");
int e = 6;
boolean f = (e<7)&&(e++<10);
System.out.println(e);
System.out.println(f);
System.out.println("===============================================");
int g = 4;
boolean h = (g<5) || (g++<6);
System.out.println(g);
System.out.println(h);
System.out.println("===============================================");
int g1 = 4;
boolean h1 = (g1<3) || (g1++<6);
System.out.println(g1);
System.out.println(h1);
}
}
- 位运算符:& | ^ ~ >>(左移) <<(右移) >>>
public class Demo06 {
public static void main(String[] args) {
System.out.println(2<<3);
System.out.println(3<<1);
System.out.println(3<<2);
System.out.println(3<<3);
System.out.println(3<<4);
System.out.println(2<<7);
}
}
public class Demo08 {
public static void main(String[] args) {
int score = 60;
String type = score < 60 ? "不及格" : "及格";
System.out.println(type);
}
}