int num1 = 4, num2 = 5;
if( num1 == num2)
System.out.print(“The numbers are the same.”);
else
System.out.print(“The numbers aren’t the same”);
Note: The boolean operator( ==), isn’t the same as the assignment operator(=).
A boolean operator asks a question, while an assignment operator executes a command. The boolean operator in this example determines if num1 is equal to num2.
The assignment statement doesn’t produce other results.
Values that can be compared using boolean statements:
==
(equal)!=
(not equal)<
(less than)<=
(less than or equal to)>
(greater than)>=
(greater than or equal to)==The boolean statement produces a truth value based on the comparison that it conducts.==
Sometimes, however, we might want to create a more complicated condition. This is referred to as a compound condition. They include at least one boolean operator.
Common Compound Conditions:
&&
- logical and||
- logical or!
- logical not==
- is equal to!=
- is not equal toEx: Consider the following boolean expression, (X && !Y) || (!X && Y). Which of the following conditions will always cause the expression to evaluate to true.
Ex: What will be the truth value of (! p && ! q) || (p || q)?
The way that if statements work and function applies to all control statements! Make sure you really understand how it works!
DeMorgan’s Laws are used to help simplify Boolean expressions.
Truth Table for combinations of Boolean Conditions:
A | B | A&&B | A||B | !A | !B | !(A&&B) | !A||!B |
---|---|---|---|---|---|---|---|
T | T | T | T | F | F | F | F |
T | F | F | T | F | T | T | T |
F | T | F | T | T | F | T | T |
F | F | F | F | T | T | T | T |
\