Using Logical AND and OR
You can create “compound if statements” that make even more intelligent decisions, using AND and OR. First we will look at how to use AND. In Java, logical AND is represented by &&.
Using If Statements with AND
First, we will consider if statements that make use of AND. For example, say you wanted to create an if statement that would only process if x were in the range between 10 and 100. You could do this with an if-statement using an AND. The following if-statement would do this.
if( (x>=10) && (x<=100) )
{
System.out.println(" x is between 10 and 100");
}
The above if-statement would be read “if x is greater than or equal to 10 and x is less than or equal to 100”, do this.
For the AND statement to be true, both sides must be true. Table 5.1 summarizes the AND statement.
Table 5.1: Truth Table for x && y (AND)
| x | y | x && y |
|---|---|---|
| false | false | false |
| false | true | false |
| true | false | false |
| true | true | true |
Using If Statements with OR
Now we will consider if statements that make use of OR. For example, say you wanted to create an if statement that would only process if x were equal to 10 or 100. You could do this with an if-statement using an OR. The following if-statement would do this.
if( (x==10) || (x==100) )
{
System.out.println(" x is either 10 or 100");
}The above if-statement would be read “if x is equal to 10 or x is equal to 100”, do this.
For the OR statement to be true, both one-side must be true. Table 5.2 summarizes the OR statement.
Table 5.2: Truth Table for x || y (OR)
| x | y | x || y |
|---|---|---|
| false | false | false |
| false | true | true |
| true | false | true |
| true | true | true |
By using both AND and OR you can create if statements that make more complex decisions.




