Java Selection Statements
Selection Statements are used in Java to enable programs to have structured decision making capabilities where a particular block of code is executed when an expression is true. In this section we will discuss:
- if statements
- Nested-if statements
- if-else statements
- if-else-if statements
- Switch-case statements
- Jump statements
- break
- continue
Selection statements enable simple or complex decision making within your program by controlling its code execution flow based upon conditions known only during run time. In real life, you are doing this kind of thing many times a day. Let’s you are going out, you might ask yourself if it is raining I will bring an umbrella. By asking yourself that question you have essentially created an if statement where the condition is if it is raining and if that is true the code you execute is to bring an umbrella. If you think about your average day you can probably think of tens or even hundreds of these type of decisions that you routinely make every day.
When executing selection statements, Java uses operators to test if an expression is true or false. For example, to check if two variables are the same or if one is larger or smaller than the other. Useful if statement operators are:
Condition | Operator | Example: int num1 = 5; int num2 = 10; |
---|---|---|
Equal To - num1 is equal to 5 | == | num1 == 5 |
Not Equal To - num1 is not equal to 10 - num2 is not equal to 4 | != | num1 != 10 num2 != 4 |
Is Less Than - num1 is less than 6 - num2 is less than 11 | < | num1 < 6 num2 < 11 |
Is Less Than or Equal To - num1 is less or equal to 5 - num2 is less than or equal to 6 | <= | num1<= 5 num2<= 6 |
Is Greater Than - num1 is greater than 1 - num2 is greater than 4 | > | num1 > 1 num1 > 4 |
Is Greater Than or Equal To - num 1 is less than or equal to 4 - num2 is less than or equal to 5 | >= | num1 >= 4 num1>= 5 |
AND - num1 is less than 6 AND num2 is greater than 6 | && | (num1 < 6) && (num2 > 6) |
OR - num1 is less than 6 OR num2 is greater than 11 | || | (num1 < 6) || (num2 > 11) |
NOT - num1 is NOT equal to 34 - num2 is NOT equal to 6 | ! | ! (num1 =34) ! (num2 = 6) |
What you will learn
In this lesson we discussed what selection statements are and why you might use them in Java. We started with the basic if statement and expanded our understanding to include nested-if statements, if-else statements, and if-else-if statements to enable us to build more complex and powerful selection statements into our programs. We also discussed the switch-case statement as an alternative to, or even compliment, an if statement structure. And we went further by exploring jump statements and the use of break and continue that can enable your program to have enhanced structured decision making capabilities.