java当中的逻辑运算符,&&(短路与)和&表示逻辑与,||(短路或)和|表示逻辑或
&&和&都可以表示逻辑与,但他们是有区别的,共同点是他们两边的条件都成立的时候最终结果才是true;
不同点是&&只要是第一个条件不成立为false,就不会再去判断第二个条件,最终结果直接为false,而&判断的是所有的条件;
测试&&:
- package test;
-
- public class Test{
- public static void main(String[] args){
- int i = 23;
- int j = 21;
- if ((i == j) && (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
输出的结果为:没有报错
正常情况下100 / 0 == 0是会报错的,而上面的示例就没有报错,就是因为&&的第一个条件不成立,后面的一个条件被短路了,所以程序没有报错
- package com.test;
-
- public class Test {
-
- public static void main(String[] args) {
- int i = 23;
- int j = 23;
- if ((i == j) && (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
当把i和j的值改成一样的时候,程序就会报错了
- Exception in thread "main" java.lang.ArithmeticException: / by zero
- at com.test.Test.main(Test.java:8)
-
说明&&的第一个条件成立的时候还会去判断第二个条件,两个条件都成立的时候最终结果才是true
测试&:
- package com.test;
-
- public class Test {
-
- public static void main(String[] args) {
- int i = 23;
- int j = 21;
- if ((i == j) & (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
- package com.test;
-
- public class Test {
-
- public static void main(String[] args) {
- int i = 23;
- int j = 23;
- if ((i == j) & (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
上面的两段代码的结果都会报错,证明&是判断所有的条件
||和|都表示逻辑或,共同点是只要两个判断条件其中有一个成立最终的结果就是true,区别是||只要满足第一个条件,后面的条件就不再判断,而|要对所有的条件进行判断。
测试||:
- package com.test;
-
- public class Test {
-
- public static void main(String[] args) {
- int i = 23;
- int j = 23;
- if ((i == j) || (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
输出结果为:1
测试|:
- package com.test;
-
- public class Test {
-
- public static void main(String[] args) {
- int i = 23;
- int j = 23;
- if ((i == j) | (100 / 0 == 0))
- System.out.println("1");
- else
- System.out.println("没有报错");
- }
- }
程序会报错