运算符
运算符
算数运算符
+,-,*,/,%(取余),++,--
赋值运算符
=
关系运算符
<,>,>=,<=,==(判断是否相等),!=instanceof(不等于)
逻辑运算符(与或非)
&&,!,||
位运算符
&,|^,~,>>,<<,>>>
条件运算符
?:
扩展赋值运算符
+=,-=,*=,/=
``
package oprateor;
public class Demo04 {
public static void main(String[] args) {
//++ -- 自增 自减 一元运算符
int a=3;
int b=a++;//执行完这行代码后,先给b赋值,再自增
//a++ a=a+1;
System.out.println(a);
//++a a=a+1;
int c=++a;//执行这行代码前,先自增,再给c赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3 2*2*2,很多运算,会使用工具类操作
double pow=Math.pow(3,2);
System.out.println(pow);
}
}
``
package oprateor;
//逻辑运算符
public class Demo05 {
public static void main(String[] args) {
//与(and)或(or)非(取反)
boolean a=true;
boolean b=false;
//用+将两个字符串拼接起来
System.out.println("a && b:"+(a&&b));//逻辑与运算:两个变量都为真,结果才为true
System.out.println("a || b:"+(a||b));//逻辑或运算:两个变量有一个为真,结果才为true
System.out.println("!(a && b):"+!(a&&b));//如果是真,则变为假,如果是假则变为真
//短路运算
int c=5;
boolean d=(c<4)&&(c++<4);//前面已经错了,不会继续执行后面的c++
System.out.println(d);
System.out.println(c);//5
}
}
``
package oprateor;
public class Demo06 {
public static void main(String[] args) {
/*
A=0011 1100
B=0000 1101
A&B OOO0 1100 如果都是1 才是1
A|B 0011 1101 如果只有一个不为0 就是1
A^B 0011 0001 相同则为0,不同则为1
~B 1111 0010 取反
2*8=16
<< *2
>> /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
*/
System.out.println(2<<3);
}
}
``
package oprateor;
public class Demo07 {
public static void main(String[] args) {
int a=10;
int b=20;
a+=b;//a=a+b;
a-=b;//a=a-b;
System.out.println(a);
//字符串连接符 + ,String +两侧出现string类型,会自动转换为string类型连接
System.out.println(""+a+b);// 1020 字符串在前面,后面拼接
System.out.println(a+b+"");// 30 字符串在后面,前面继续运算
}
}
``
package oprateor;
//三元运算符
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);
}
}
浙公网安备 33010602011771号