AP Computer Science Java: Lesson 2.4
Conditional Statements - Logical Operators


Lesson 2.4 - Logical Operators

Purpose: To learn how to use Java's AND & OR operators

Multiple Conditions
  Sometimes it is necessary to evaluate more than one condition in an if statement. For example, to determine whether a person is a teenager, we need to find out if their age is at least 13, but also less than 20. The following if statement would not be sufficient for this task:

   if(age >= 13)
   {
      System.out.println("You are a teenager");
   }

This won't work if age happens to be, say, 35. It will incorrectly display that a 35-year-old is a teenager since 35 is greater than 13. To correctly address this situation, we can use the logical operator AND, which has the symbol &&:

   if(age>=13 && age<20)
   {
       System.out.println("You are a teenager");
   }

The && requires that both conditions be met in order to perform the statement in the braces. So if the variable age is 35, it will not enact the display statement since 35 is not less than 20.

Using OR   When only one of two conditions needs to be true to cause some action, the AND operator is not the correct choice. For this task, the OR operator is needed. The symbol for OR is two vertical bars (||). The vertical bar symbol can be found on the backslash key, directly above the enter key. Let's look at an example in which OR will be useful.

Suppose that a game is being played in which scores were being kept for two players in integer variables called score1 and score2. Suppose further that the game is over when one of the player's scores reaches 10. The following if statement could be used to check whether the game is over:

   if(score1==10 || score2==10)
   {
      System.out.println("The game is over");
   }

The AND operator would not be appropriate here because we don't need both scores to equal 10, just one of them. It is important to note, however, that an OR will still enact the statement in braces if both conditions are true since at least one of them is true. So if both score1 and score2 equal 10, the display statement will still occur.


In closing
, when needing to evaluate more than one condition in an if statement, choose AND if both conditions need to be true and choose OR if only one of the conditions needs to be true. Be careful, as the wrong choice will yield unwanted results.

© DanShuster.com