在 Java 中,布尔“操作顺序"是什么? [英] In Java, what are the boolean "order of operations"?

查看:15
本文介绍了在 Java 中,布尔“操作顺序"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们举一个对象Cat的简单例子.我想确定非空" cat 是橙色还是灰色.

Let's take a simple example of an object Cat. I want to be sure the "not null" cat is either orange or grey.

if(cat != null && cat.getColor() == "orange" || cat.getColor() == "grey") {
//do stuff
}

我相信 AND 首先出现,然后 OR.不过我有点模糊,所以这是我的问题:

I believe AND comes first, then the OR. I'm kinda fuzzy though, so here are my questions:

  1. 有人可以指导我完成此声明,以便我确定我明白会发生什么吗?

  1. Can someone walk me through this statement so I'm sure I get what happens?

另外,如果我添加括号会发生什么;这会改变操作顺序吗?

Also, what happens if I add parentheses; does that change the order of operations?

我的操作顺序会因语言而异吗?

Will my order of operations change from language to language?

推荐答案

Java 教程有一个列表说明 运算符优先级.将首先评估相等运算符,然后是 &&,然后是 ||.括号将在其他任何内容之前进行评估,因此添加它们可以更改顺序.这通常在不同语言之间几乎相同,但仔细检查总是一个好主意.

The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.

您没有预料到的行为的微小变化会导致您花费一整天的时间进行调试,因此最好将括号放在适当的位置,这样您就可以确定评估的顺序是什么.

It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.

这篇关于在 Java 中,布尔“操作顺序"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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