Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what are the boolean "order of operations"?

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 } 

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

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

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

  3. Will my order of operations change from language to language?

like image 558
Stephano Avatar asked Feb 15 '10 02:02

Stephano


People also ask

What is the order of operations for Boolean operations?

The order of operations for Boolean algebra, from highest to lowest priority is NOT, then AND, then OR. Expressions inside brackets are always evaluated first.

What is the order of operations in Java?

The operator precedence is responsible for evaluating the expressions. In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

What are the 3 types of Boolean operations?

There are three basic Boolean search commands: AND, OR and NOT. AND searches find all of the search terms. For example, searching on dengue AND malaria AND zika returns only results that contain all three search terms. Very limited results.

What is Boolean operation in Java?

Boolean is the java data type. Boolean variables are declared using the boolean keyword, which accepts true or false. By default, it has the value false. It was used in the situation where you want one value out of two values. For example: On / Off, True / False, 1 /0, Yes / No.


1 Answers

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.

like image 155
Bill the Lizard Avatar answered Sep 23 '22 08:09

Bill the Lizard