自增自减运算符++,–
public class Demo04 {
public static void main(String[] args) {
//++ -- 自增自减 一元运算符
int a = 3;
int b = a++; //执行完代码后,先给b赋值,再自增
// b = a , a = a+1
System.out.println(a); //a=4
//a = a+1 , c = a
int c = ++a;//执行完代码后,先自增,再给c赋值
System.out.println(a); // a = 5
System.out.println(b); // b = 3
System.out.println(c); // c = 5
}
}
初识Math
幂函数
double pow = Math.pow(2, 3);
//2^3 = 2*2*2 = 8
System.out.println(pow);
//Math.pow(2,3) 按Alt+Enter 跳出提示,再按Enter
逻辑运算符
package operator;
public class Demo05 {
public static void main(String[] args) {
//与and 或or 非取反
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)); //非
//短路运算
int c =5;
boolean d = (c<4)&&(c++<4);
System.out.println(d); //false
System.out.println(c); //c = 5
// d&&c中,d为假时,自动判断整式为假,c不参与运算
}
}
位运算符
**二进制,每一位间比较,输出为0或1 **
package operator;
public class Demo06 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
------------------------------------------
位与 A&B = 0000 1100
位或 A|B = 0011 1101
异或,相同为零,不同为1
A^B = 0011 0010
取反 ~B = 1111 0010
左移<< *2
右移>> /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
*/
System.out.println(
3<<3 //=3*2*2*2=3*2^3
//0000 0011-->0000 0110-->0000 1100
);
}
}
扩展赋值运算符
package operator;
// += -= *= /=
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b;//a = a+b
System.out.println(a); //30
System.out.println(a+=b); //50
//字符串连接符 +
System.out.println(a+b); //70
System.out.println(""+a+b); //5020
System.out.println(a+b+""); //70
}
}
注意String所在位置,若在 + 左边,则其后所有都为字符串形式,在右边,则前边照常运算
三元运算符
条件运算符 ? :
package operator;
//三元运算符
public class Demo08 {
public static void main(String[] args) {
//x ? y : z
//如果x==true,则结果为y,否则结果为z
int score = 80;
String type = score <60 ?"不及格":"及格";//必须掌握
// if
System.out.println(type);//及格
}
}