if, else if, and else
Consider the following code segment:
In the code segment:
- if evaluates only if the condition inside the brackets evaluates to true.
- The program above will print “Grade A” if score >= 90 evaluates to true
- else if statements must come after if statements. The condition is evaluated if both the if statement was not executed and the condition in the brackets evaluates to true.
- The program above will print “Grade B” if score >= 90 evaluates to false and score >= 80 evaluates to true
- You can have multiple else if statements in sequence. In that case, at most one will be evaluated (the one which is on top)
- The program will print “Grade C” if score >= 90 and score >= 80 evaluate to false, and score >= 70 evaluates to true.
- else statements evaluate only if all the conditions above were false.
- The program will print “Grade D” if score >= 90, score >= 80 and score >= 70 all evaluate to false.
Logical Operators
Learn about combining conditions using logical operators like &&, ||, and !.
| Logical Operators | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Java | Name | Logic Table | ||||||||||||||||
| && | Logical AND |
|
||||||||||||||||
| || | Logical OR |
|
||||||||||||||||
| ! | Logical NOT |
|
||||||||||||||||
De Morgan's Laws
| De Morgan's Laws | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| Rule | English | Symbolic Form | |||||||
| Law 1 | “Not (A and B) is the same as (Not A or Not B)” | !(A && B) = !A || !B | |||||||
| Law 2 | “Not (A or B) is the same as (Not A and Not B)” | !(A || B) = !A && !B | |||||||
(De Morgan's Law - Theorem, Proofs, Formula & Examples | GeeksforGeeks)
We can use De Morgan's laws to simplify complex logical operations.
For example, let's say we have the following logical operation:!(sunny || windy)
We see that it is very hard to understand what the above logical expression really means, however, with De Morgan's laws we can easily find out what the expression simplifies to.
We first apply the 2nd Law (!(A || B) ≡ !A && !B):
!(sunny || windy) → !sunny && !windy