运算符(operators)
Java语言支持如下运算符:
-
算术运算符:+ , - , * , / , % , ++ , –
-
赋值运算符:=
-
关系运算符:> , < , >= , <= , != , == , instanceof
-
逻辑运算符:&& , || , !
-
位运算符:& , | , ^ , ~ , >> , << , >>>
-
条件运算符:? , ;
-
扩展运算符:+= , -= , *= , /=
//算术运算符
public class Test1 {
public static void main(String[] args) {
int a =1;
//执行这行代码后,先给b赋值,之后再给a自增
int b = a++; //输出 b为 1, a为 2
//执行这行代码前,先给a自增,再给c赋值
int c = ++a; //输出 c为 3 ,a为 3
//幂运算 2^3=8
double pow = Math.pow(2,3);
}
}
关系运算符: instanceof
-
对象实例不能是基础数据类型(ps: double d = 0.01; boolean b = d instanceof Double -->报错);
-
对象实例和右边的类不在同一个继承树上(PS: String s =“123”; boolean b = s instanceof Double -->报错 );
-
实例对象为null的时候,instanceof任何一个类都是false(PS:1);
-
一个实现类对象,instanceof实现类和父接口都为true,instanceof实现类子类为false(PS:2);
-
向上造型,接口的引用指向实现类的对象,instanceof实现类和接口为true,instanceof实现类的子类为false(PS:3);
-
向上造型,父类引用指向子类对象,instanceof实现类和父类,父类的上级接口都为true(PS:4);
-
实现类对象,instanceof当前类和向上所有父类都为true(PS:5);
(向上造型:父类引用指向实现类对象或接口引用指向实现类的对象;向下造型:指向子类对象的父类引用赋予子类引用,需要强制转换。)
//关系运算
interface A {
}
class B implements A{
}
class C extends B{
}
public class Test3 {
public static void main(String[] args) {
A a = null;
System.out.println("1: "+ String.valueOf(a instanceof A));//输出为false
B b = new B();
System.out.println("2: "+ String.valueOf(b instanceof B));//输出为true
System.out.println("2: "+ String.valueOf(b instanceof A));//输出为true
System.out.println("2: "+ String.valueOf(b instanceof C));//输出为false
A a1 = new B();
System.out.println("3: "+ String.valueOf(a1 instanceof A));//输出为true
System.out.println("3: "+ String.valueOf(a1 instanceof B));//输出为true
System.out.println("3: "+ String.valueOf(a1 instanceof C));//输出为false
B b1 = new C();
System.out.println("4: "+ String.valueOf(b1 instanceof B));//输出为true
System.out.println("4: "+ String.valueOf(b1 instanceof C));//输出为true
System.out.println("4: "+ String.valueOf(b1 instanceof A));//输出为true
C c = new C();
System.out.println("5: "+ String.valueOf(c instanceof B));//输出为true
System.out.println("5: "+ String.valueOf(c instanceof A));//输出为true
System.out.println("5: "+ String.valueOf(c instanceof C));//输出为true
}
逻辑运算符:&& , || , !:
1. &&:逻辑与运算,两个变量都为true,才为true;
2. || :逻辑或运算, 两个变量中一个为true,就为true;
3. ! :如果为true,则为false,如果为false,则为true;
位运算:
//位运算
public class Test2 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
-----------------------
A&B = 0000 1100(与运算 两个都为1才为1)
A|B = 0011 1101(或运算 一个为1就为1)
A^B = 0011 0001(异或运算,相同为0,不相同为1)
~B = 1111 0010(去反,完全相反)
问题:2*8怎么运算最快?
答: 2<<3
效率极高!!
<< *2
>> /2
*/
System.out.println(32>>3);//32/2/2/2 ->输出为4
System.out.println(2<<3);//2*2*2*2 —>输出为16
}
}
扩展运算符:
格式:type a= x ? y : z --> x为true则a为y,x为false则a为z