今天看了看java编程思想第三版,在第三章中讲到逻辑运算符时提到了一个我以前没听过的名次“短路”,那到底什么是短路呢?先看看下面的代码
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
上面的代码会输出什么结果呢?如果在没看“短路”之前我会给出下面的结果
come in and a=0
come in and a=1
result is false
因为我认为这里面的两个test方法都会执行,如果你觉得我的结果是正确的,那么你和我一样对“短路”不了解,运行代码实际的输出结果是
come in and a=0
result is false
为什么会这样呢?我举个简单的例子
![](/Images/OutliningIndicators/None.gif)
上面的语句会输出什么呢?你肯定一眼就能看出是false,因为在这些与运算中有一个false所以不用在往下看就知道返回结果肯定是false,其实这里就有"短路"了,实际上if所执行的操作和我们的思维是一样的。
首先执行test(0)返回的是false而java有判断出后面的是个与操作,所以不管后面是真还是假都不影响结果,索性就不做判断了,这样做在性能上也会有所提升。