Java逻辑运算符短路 [英] Java logical operator short-circuiting

查看:120
本文介绍了Java逻辑运算符短路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪一组是短路的,这究竟是什么意味着复杂的条件表达式是短路的?

Which set is short-circuiting, and what exactly does it mean that the complex conditional expression is short-circuiting?

public static void main(String[] args) {
  int x, y, z;

  x = 10;
  y = 20;
  z = 30;

  // T T
  // T F
  // F T
  // F F

  //SET A
  boolean a = (x < z) && (x == x);
  boolean b = (x < z) && (x == z);
  boolean c = (x == z) && (x < z);
  boolean d = (x == z) && (x > z);
  //SET B    
  boolean aa = (x < z) & (x == x);
  boolean bb = (x < z) & (x == z);
  boolean cc = (x == z) & (x < z);
  boolean dd = (x == z) & (x > z);

}


推荐答案

&& || 运营商短路,这意味着他们不评估右侧没有必要。

The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary.

& | 运算符,当用作逻辑运算符时,总是评估双方。

The & and | operators, when used as logical operators, always evaluate both sides.

每个运算符只有一个短路情况,它们是:

There is only one case of short-circuiting for each operator, and they are:


  • false&& ... - 没有必要知道右边是什么,结果必须是 false

  • true || ... - 没有必要知道右边是什么,结果必须是 true

  • false && ... - it is not necessary to know what the right hand side is, the result must be false
  • true || ... - it is not necessary to know what the right hand side is, the result must be true

让我们在一个简单的例子中比较一下这个行为:

Let's compare the behaviour in a simple example:

public boolean longerThan(String input, int length) {
    return input != null && input.length() > length;
}

public boolean longerThan(String input, int length) {
    return input != null & input.length() > length;
}

第二个版本使用非短路运算符& 并且如果输入,将抛出 NullPointerException null ,但第一个版本将返回 false ,没有例外;

The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception;

这篇关于Java逻辑运算符短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆