运算符
-
算术运算符
+,-,*,/,%(取余数),++,–
2.赋值运算符
=
3.关系运算符
>,<, >=,<=,==(等于),!=(不等于),instanceof
4.逻辑运算符
&&,||,!(与或非)
– ++
++ 自增 – 自减 一元运算符
public class operator {
public static void main(String[] args) {
int a=3;
int b=a++;//a++ a=a+1 执行代码后,先赋值,再自增
int c=++a;//a++ a=a+1 执行代码前,先自增,再赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
与或非运算
public class operator {
//逻辑运算符 与或非
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)));//如果是真,则假;如果是假,则为真
//短路运算
int c=5;
boolean d=(c<4)&&(c++<5);//在c<4时已经错了,后面的c++就不执行了,所以c=5
System.out.println(c);
System.out.println(d);
}
}
位运算
package Package;
public class Demon01 {
public static void main(String[] args) {
/*
a= 0011 1100
b= 0000 1101
a&b=0000 1100
a|b=0011 1101
a^b=0011 0001
~b= 1111 0011
2*8=16 2*2*2*2
<< *2 左移
>> /2 右移
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 0101 5
0000 0110 6
0000 0111 7
0000 1000 8
0001 0000 16
*/
System.out.println(2<<3);//输出16
}
}
拓展运算符
int a=10;
int b=20;
a+=b;//a=a+b
a-=b;//a=a-b
System.out.println(a);
}
字符串连接符
+,string
public static void main(String[] args) {
int a=10;
int b=20;
System.out.println(""+a+b);//输出1030
System.out.println(a+b+"");//输出30
三元运算符
package Package;
public class Demon02 {
public static void main(String[] args) {
//x ? y : z
//如果X为ture,则结果为Y,否则为z
int score = 80;
String t = score < 60 ? "不及格" : "及格";
System.out.println(t);
}
}