运算符
-
算数运算符:+、-、*、/、%(模运算)、++、--
-
赋值运算符:=
-
关系运算符:>、<、>=、<=、==(java的等于要用,两个等于号)、!= instanceof (不等于)
-
逻辑运算符:&&、||、!
二元运算符
public static void main(String[] args) { //二元运算符 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); }
输出结果:30 -10 200 0.5
类型转换
public static void main(String[] args) { long a = 1213131313131L; int b =133; short c = 16; byte d =8; System.out.println(a+b+c+d);// long 类型 每个都是long System.out.println(c*d);//int类型 System.out.println((double) c+d);//强制转换 (double) 不能把String类型,(cast)转换int 类型 }
输出结果 : 1213131313288 128 24.0
模运算 取余
//关系运算符返回的结果 :正确 ,错误 通过布尔值表示 //if //取余:模运算 public static void main(String[] args) { int a = 10; int b = 20; int c = 21; System.out.println(a>b); //a大于b 输出结果 布尔值 System.out.println(a%b);//模运算 取(a/b)的余数 System.out.println(a<b);//a小于b 输出结果 布尔值 System.out.println(a==b); //a等于b System.out.println(a!=b);//a不等于b }
++ -- 自增 自减
public static void main(String[] args) { //++ -- 自增 自减 int a = 3; //int a = a+1 隐藏未运行 System.out.println(a); int b = a++; //先计算再自增 int c = ++a;//先自增再计算 System.out.println(a); System.out.println(b); System.out.println(c); //幂运算 2^3 2*2*2 = 8 double pow = Math.pow(2,3); System.out.println(pow); //很多运算我们会使用工具类来操作 }
运算结果:3 5 3 5 8.0
逻辑运算符
//逻辑运算符 public static void main(String[] args) { //与& (and) 或| (or) 非!(取反) boolean a = true; boolean b = false; System.out.println("a && b:"+(a&&b));// ("a && b:"+(a%%b)) //逻辑与运算:两个变量都为真,结果才为true System.out.println("a || b:"+(a||b));//("a || b:"+(a||b)) //逻辑或运算:两个变量有一个为真,结果才为true System.out.println("!(a %% b):"+!(a&&b));//("!(a && b ):"+!(a&&b)) //取反运算:如果是真,则变为假,如果是假则变为真 //短路运算:a = ture b = false b在前 直接算错,不会执行后面 int c = 5; boolean d = (c<4)&&(c++<4); //c<4 错误公式 不计算后面(c++<4) C>4 正确 (c++<4)先计算 再自增 C+1=6 System.out.println(d); System.out.println(c); }
运算结果:a && b:falsea || b:true!(a %% b):truefalse5
位运算
public static void main(String[] args) { //位运算: &(与) |(或) ^(亦或) ~(取反) 二进制位运算 /* A = 0011 1100 二进制的数字 B = 0000 1101 A&B = 0000 1100 与运算:两个都是1 才为1,否则就是0 A|B = 0011 1101 或运算:对应位都是0 才为0,有一个是1,直接变1 A^B = 0011 0001 亦或运算:两位相同则为0,不相同则为1 ~B = 1100 0001 取反运算:完全相反 两位相同则变1,不相同则变0 2*8 = 16 2*2*2*2 位运算效率极高 <<(左移) 把数字*2 >>(右移) 把数字/2 0000 0000 0 默认0 0000 0001 1 01开头默认1 0000 0010 2 逢二进一 0000 0011 3 +1 0000 0100 4 +1 进一位 0000 1000 8 0001 0000 16 向左移位 就变大 */ System.out.println(2<<3); System.out.println(4<<3); }
运算结果:16 32
三元运算符
//三元运算符
public static void main(String[] args) {
// x ? y : z
//如果x==true,则结果为y,否则结果为z
int score = 80; //score 成绩
String type = score <60 ?"不及格":"及格";
//if
System.out.println(type);
int salary = 4000;// salary 薪水
String doublean = salary<4000?"不及格":"及格";
System.out.println(doublean);
}