在Java中的运算符,基本上可分为算术运算符、关系运算符、逻辑运算符、位运算符、赋值运算符、转型运算符等。
在进行算术运算操作的时候,需要注意数据类型转换。
public class Test{
public static void main(String[] args) throws Exception{
int i=1;
long l=2;
int k2=i+l;//不能通过编译,因为运算后的结果是long类型
int k1=(int)(i+l);
}
}
逻辑运算符和位运算符的一个重要的区别就是逻辑运算符会出现短路的情况。
接下来再用一个例子说一下三元运算符:
public class Test{
public static void main(String[] args) throws Exception{
int k1=3;
boolean p=(k1==3)?true:false;//如果括号中返回为true,则使用true来赋值给p,如果括号中的结果为false,则使用false来赋值给p
System.out.print(p);
}
}
最后介绍一下 instanceof ,它用来在运行时指出对象是否是特定类的一个实例。用法如下:
public class Test{
public static void main(String[] args) throws Exception{
A a=new A();
B b=new B();
boolean b1=a instanceof A;//true
boolean b2=a instanceof A1;//false
//boolean b3=b instanceof A;//不能通过编译,instanceof只能用于有继承关系的类之间。
System.out.println(b1);
System.out.println(b2);
}
}
class A{
}
class A1 extends A{
}
class B{
}