A condition in an if-else statement is any expression that produces a result of type boolean. That is, it produces either true or false.
You can use comparison operators to compare things. The Java comparison operators are as follows.
Expression | Meaning |
---|---|
x > y | This is true if x is strictly greater than y |
x < y | This is true if x is strictly less than y |
x >= y | This is true if x is greater than or equal to y |
x <= y | This is true if x is less than or equal to y |
x == y | This is true if x is the same as y |
x != y | This is true if x is not the same as y |
Notice that use use two consecutive equal signs to ask whether two values are the same. Be careful about that. Writing x = y is not the same as writing x == y.
Also, you cannot put any spaces inside a relational operator. For example, you are not allowed to write x = = y.
Questions.
What is the value of expression 24 <= 25? Answer[12]
What is wrong with expression 24 =< 25? Why isn't it allowed? Answer[13]
What is wrong with expression 24 !> 25? Why isn't it allowed? Answer[14]
Is expression 24 > 25 allowed? Answer[15]
Do you think that you are allowed to write expression x + 4 > 2 * y? Or do you have to compare just constants or variables, not more complicated expressions? Answer[16]
(Trick question, so be careful) Suppose that variable w currently contains 68. What is the value of expression w = 64? Answer[17]
Sometimes you want to combine or modify conditions. You can use the following notation in Java.
Expression | Meaning |
---|---|
A && B | This is true if both A and B are true. However, if A turns out to be false, then B is not computed at all, since if A is false, the computer knows that A && B must also be false. |
A || B | This is true if either A or B or both are true. If A turns out to be true, then B is not computed at all, since, if A is true, then the computer already knows that A || B is true. |
!A | This is true if A is false, and is false if A is true. |
Questions.
Suppose that x holds 19 and y holds 84. What is the value of expression x > y || y > 0? Answer[18]
In mathematics, you often write multiple comparisons, such as x > y > z. But Java only allows you to compare two values at once. How can you write a Java expression that is true if x > y and y > z? Answer[19]