java中&和&&的区别
For integer arguments, the single ampersand (“&”)is the “bit-wise AND” operator. The double ampersand (“&&”) is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) “logical AND” operator while the double ampersand (“&&”) is the “conditional logical AND” operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
这么看来, &两边也可以用布尔值的参数,这时候就不在是按”位and” 操作. 而是逻辑的and 操作符. 但是&& 和 & 在逻辑and时,还是有些不同的. 如下代码, 将&& 和 & 都试一下,便知道原因了. 不过在代码书写中, 还是不见意在逻辑and时, 使用&. 否则会让人读代码和维护代码时, 降低了可维护性.
public class test { public static void main(String[] args) { boolean a = false; if(a && (new test()).test()) // && 换成 & 再执行一遍 { System.out.println("true"); } else{ System.out.println("false"); } } public boolean test() { System.out.println("test function executed"); return true; } }
========结果=========
false
把&&换成&
========结果=========
false
test function executed
此篇文章已被阅读3155 次