运算符
package Operator;
public class Demo01 {
//二元运算
public static void main(String[] args) {
int a = 10;
int b = 15;
int c = 20;
int d = 25;
System.out.println(a+b);//25
System.out.println(a*b);//150
System.out.println(d-a);//15
System.out.println(c/a);//2
System.out.println(a/(double)c);//0.5
}
}
package Operator;
public class Demo02 {
public static void main(String[] args) {
//在运算中最小采用lnt类型
long e = 2345465;
int f = 1234;
short g = 2345;
byte h = 12;
System.out.println(e+f+g+h);//long类型
System.out.println(f+g+h);//int类型
System.out.println(g+h);//int类型
}
}
package Operator;
public class Demo03 {
public static void main(String[] args) {
//关系运算 输出的是布尔值 true false
int a =10;
int b = 20;
System.out.println(a<b);
System.out.println(a>b);
System.out.println(a==b);
System.out.println(a!=b);
//求余,模运算
System.out.println(21%10);//输出1 求余数,21/10=2余1
}
}
package Operator;
public class Demo04 {
public static void main(String[] args) {
//++ 自增 ; -- 自减 一元运算符
int a = 39;
int b =++a;//++或--在前面,先进性运算,再赋值。a=39+1=40,b=a=40;
int c = a++;//++或--再后面,先进行赋值,再运算。c=a=40,a=40+1=41;
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 math.pow() 很多运算我们会使用一下工具类来操作 列如math类
double e = Math.pow(3, 5);
System.out.println(e);
}
}
package Operator;
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));//逻辑非,取反,假变真,真变假。
//短路运算f:在进行逻辑&&运算时,如果第一个为假,则不会进行的二个运算。
int c = 5;
System.out.println(c<1&&c++>0);//false
System.out.println(c);//5
}
}
package Operator;
public class Demo06 {
public static void main(String[] args) {
/* 位运算
& | ^ ~
* A=0000 1100
* B=0011 1101
* -------------------------------------------
* A&B 0000 1100 两者都为1 才取1
* A|B 0011 1101 有一个为一就为1
* A^B 0011 0001 相同为0,相反为1
* ~B 1100 0010 取反
* =======================================
* 面试题 2*8最快的算法 2*8=2*2*2*2
* << 左移3位
* 原因:通过计算机底下代码进行运算
* 0000 0000 0
* 0000 0001 1
* 0000 0010 2
* 0000 0011 3
* 0000 0100 4
* 0000 1000 8
* 0001 0000 16
*
* 重点:<< *2 左移=乘2
* >> /2 右移= 除2
* 2*8=2*2*2*2
* 通过二进制进行预算效率极高。
* */
System.out.println(2<<3);//16
}
}
package Operator;
public class Demo07 {
//字符串连接 + ,string
public static void main(String[] args) {
int a=10;
int b = 20;
System.out.println(""+a+b);//1020 如果空的字符串在前面,它会把后面转换成字符型在进行拼接。
System.out.println(a+b+"");//30 如果空的字符串在后面不会影响前面的结果。
}}
package Operator;
public class Demo08 {
public static void main(String[] args) {
//三元运算符
//x ? y : z;
//如果x == true 结果就是y 否则(结果为falot)是z
int score = 95;
String type=score >60? "及格":"不及格";
System.out.println(type);
String type2=score>90? "面试成功":"一条咸鱼";
System.out.println(type2);
}
}
java运算优先级
一般而言,单目运算符优先级较高,赋值运算符优先级较低。算术运算符优先级较高,关系和逻辑运算符优先级较低。多数运算符具有左结合性,单目运算符、三目运算符、赋值运算符具有右结合性。
浙公网安备 33010602011771号