短路运算符就是我们常用的“&&”、“||”,一般称为“条件操作”。
class Logic{
public ststic void main(String[] args){
int a=1;
int b=1;
if(a<b && b<a/0){
System.out.println("Oh,That's Impossible!!!");
}else{
System.out.println("That's in my control.");
}
}
}
“&&”运算符检查第一个表达式是否返回“false”,如果是“false”则结果必为“false”,不再检查其他内容。
“a/0”是个明显的错误!但短路运算“&&”先判断“a<b”,返回“false”,遂造成短路,也就不进行“a/0”操作了,程序会打出"That's in my control."。这个时候,交换一下“&&”左右两边的表达式,程序立即抛出异常“java.lang.ArithmeticException: / by zero”。
class Logic{
public ststic void main(String[] args){
int a=1;
int b=1;
if(a==b || b<a/0){
System.out.println("That's in my control.");
}else{
System.out.println("Oh,That's Impossible!!!");
}
}
}