In the previous lesson you learnt about using enum for constants.
Logical operators and the if statement
Frequently in programming you need to check whether a certain condition is true and perform different processing if the condition holds to when the condition does not hold. Java provides the if statement to help you achieve this:
There are several logical operators used primarily to compare primitives:.
| == | Equal to (note the double equal signs) |
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| > | Greater than |
| >= | Greater than or equal to |
The comparison operator from the above table to take note of is ==, where there are two consecutive equal symbols, and which means to check whether one value is equal to another value. A common mistake among beginners is to confuse this with the single equals operator = you used previously, and which means assignment.
- Single equals sign means assignment
- Double equals sign means comparison
The Java if statement is used to test whether a particular condition holds, where the conditional expression resolves to a boolean value of either true or false:
Braces are used to demarcate a block of code that will be executed if the condition is met. In the above example, because variable a is 3 and variable b is 4, the three blocks will be executed because the if conditions return true:
- a is not equal to b: (a != b);
- a is less than b: (a < b);
- a is less than or equal to b: (a <= b).
The other if conditions will return false and therefore the code inside those blocks will not be executed.
The above operators will work for any numeric primitive type: byte, short, int, long, float, double and char.
If your if condition is comparing two booleans you can only use == and !=:
If you only need to execute one statement when the condition is met, then the braces are optional:
if (sunny == true) System.out.println("It is sunny");
However, for clarity it is suggested that you always include the braces:
if (sunny == true) {
System.out.println("It is sunny");
}
You can abbreviate boolean comparisons to remove the second operand, for example:
Is equivalent to saying:
You can use the ! (read as "not") symbol to negate the comparison, hence:
Is equivalent to saying:
Examples in use:
In the next lesson you will learn about compound operators.