zoukankan      html  css  js  c++  java
  • java中的"短路"现象

    今天看了看java编程思想第三版,在第三章中讲到逻辑运算符时提到了一个我以前没听过的名次“短路”,那到底什么是短路呢?先看看下面的代码

    public class ShortCut
    {
        
    public static boolean test(int a)
        
    {
            System.out.println(
    "come in and a=" + a);
            
    return a > 1;
        }

        
        
    public static void main(String[] args)
        
    {
            
    if( test(0&& test(1) )
            
    {
                System.out.println(
    "result is true");
            }

            
    else
            
    {
                System.out.pringln(
    "result is fasle");
            }

        }

    }

    上面的代码会输出什么结果呢?如果在没看“短路”之前我会给出下面的结果
    come in and a=0
    come in and a=1
    result is false
    因为我认为这里面的两个test方法都会执行,如果你觉得我的结果是正确的,那么你和我一样对“短路”不了解,运行代码实际的输出结果是
    come in and a=0
    result is false
    为什么会这样呢?我举个简单的例子

    System.out.println( true && true && false && true && true );


    上面的语句会输出什么呢?你肯定一眼就能看出是false,因为在这些与运算中有一个false所以不用在往下看就知道返回结果肯定是false,其实这里就有"短路"了,实际上if所执行的操作和我们的思维是一样的。
    首先执行test(0)返回的是false而java有判断出后面的是个与操作,所以不管后面是真还是假都不影响结果,索性就不做判断了,这样做在性能上也会有所提升。

  • 相关阅读:
    Spring Boot中的测试
    从Spring迁移到Spring Boot
    在Spring Boot中配置web app
    自定义spring boot的自动配置
    Spring Boot @EnableAutoConfiguration和 @Configuration的区别
    Scala的Higher-Kinded类型
    Scala的存在类型
    Spring Boot注解
    Maven Wrapper简介
    spring boot 使用maven和fat jar/war运行应用程序的对比
  • 原文地址:https://www.cnblogs.com/interboy/p/883327.html
Copyright © 2011-2022 走看看