Thus far, we have gone over various operators that we have been using to create our Boolean expressions. However, we have been limited by only using one Boolean expression at time. In this lesson, we will take a look at logical operators.
In Java, there are 3 logical operators:
The logical operator
&& is used when we want to have two or more conditions evaluated. Let’s look at an example.
In the if statement above, we can see that we have two separate conditions that are joined by the
&& symbol. First, the boolean variable
likesCoffee is true. Next, since the first condition is met, the
&& operator moves to the 2nd condition to see if it evaluates to true. Because both of the conditions are met, the if statement prints out:
Want some more coffee?.
&& is sometimes referred to as a short circuit operator. This is due to the fact that if the first condition does not evaluate to true, then it does not bother with evaluating the 2nd. Now let’s look at an example of the OR operator
In the example above we have an OR logical operator represented as
|| in between two separate conditions. When we use an OR operator, it means that conditions do not have to be met. Instead, only one of them must be met in order for the if statement to execute its code. In this case, although
hotTemp does not evaluate to true, the if statement will still execute. This is because the
likesCoffee evaluates to true and forces the if statement to print:
An iced coffee sounds good.
The NOT logical operator
! is used to reverse values. Let’s look at an example.
In the code above, we can see that we have the NOT operator
! in front of the boolean value
hatesCoffee. This if statement translates roughly into “if the bool value hatesCoffee does not equal true, then execute code within brackets.”
As you can see, the Boolean value
hatesCoffee does indeed equal false. Therefore, the program above executes the if statement and prints
I like coffee.
In future lessons, we will start to experiment more and see examples of how these logical operators can be paired together and used with parentheses to further specify the execution criteria to suit the programmer’s specific needs.