短路与和与的区别

区别

1
2
3
4
* &&(短路与)只要有一个满足条件,后面的条件就不再判断
* &(与)对所有条件都进行判断
* ||(短路或)只要有一个满足条件,后面的条件就不再判断
* |(或)对所有条件都进行判断

&&和&例子

1
2
3
4
5
6
7
public class Test{
public static void main(String[] args){
if(100!=100 & 100/0==0){
System.out.println("Hello");
}
}
}
1
2
3
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.cn.Test001.main(Test001.java:32)

将&修改为&&:

1
2
3
4
5
6
7
public class Test{
public static void main(String[] args){
if(100!=100 && 100/0==0){
System.out.println("Hello");
}
}
}

1
2
Output:
Hello

||和|例子

1
2
3
4
5
6
7
public class Test{
public static void main(String[] args){
if(100==100 | 100/0==0){
System.out.println("Hello");
}
}
}
1
2
3
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.cn.Test001.main(Test001.java:32)

将|修改为||:

1
2
3
4
5
6
7
public class Test{
public static void main(String[] args){
if(100==100 || 100/0==0){
System.out.println("Hello");
}
}
}

1
2
Output:
Hello