Introduction
One of the most satisfying parts of writing and running a program is realizing that you are in control of the computer. However, if you reflect on the programs you’ve created so far, how much control did you truly have? While you were the one who chose which instructions to include, the order in which they were carried out wasnât really up to you. Typically, these instructions were executed sequentiallyâone after anotherâfrom the start to the end of the main
method. As you continue learning, youâll discover many situations where this strict sequence becomes limiting, and youâll want greater flexibility to determine the flow of execution.
Making Choices
Often, you’ll want your programs to make decisions between different possible actions. For instance, a program handling airline ticket requests might need to:
- show the price of the requested seats,
- provide a list of alternative flights, or
- display a message indicating no flights are available to the chosen destination.
A program that can make decisions is capable of behaving differently each time it runs, unlike programs that simply execute instructions in a fixed sequence, which behave the same way every time. As mentioned earlier, unless specified otherwise, instructions are executed one after the other in order. However, selection is a programming technique that allows you to control which instructions are executed by making decisions during runtime.
Letâs take a closer look at how to improve the roller-coaster program using selection, so that it behaves appropriately based on the riderâs age.
Original Problem:
Currently, the message "Hello Junior!"
is displayed for everyone, regardless of their age. However, we only want to show this message to children under the age of 13.
Pseudocode Solution Recap:
DISPLAY âHow old are you?â
ENTER age
IF age is under 13
DISPLAY "Hello Junior!"
DISPLAY "Enjoy your ride"
This is a classic example of selectionâdeciding which code to execute based on a condition.
Java Implementation:
Below is the updated version of the Java program using an if
statement to apply this selection logic:
import java.util.*;
public class RollerCoaster {
public static void main(String[] args) {
// declare variables
int age;
Scanner keyboard = new Scanner(System.in);
// prompt and read input
System.out.println("How old are you?");
age = keyboard.nextInt();
// use selection to guard the message
if (age < 13) {
System.out.println("Hello Junior!");
}
// this message is always displayed
System.out.println("Enjoy your ride");
}
}
Explanation:
- The
if (age < 13)
condition checks if the user is under 13. - If the condition is
true
, it executes the message"Hello Junior!"
. - The
System.out.println("Enjoy your ride");
line runs no matter what the age is.
This simple change gives your program the ability to make decisions, which is the foundation of selection control in Java.
The if
Statement in Java
The type of selection control introduced earlierâwhere a decision is made about whether to run a specific instructionâis implemented in Java using the if
statement.
General Syntax:
javaCopyEditif ( /* a test goes here */ ) {
// instructions to be executed if the test is true
}
Key Components:
- The Test (Condition):
- This must be a boolean expressionâan expression that evaluates to either
true
orfalse
. - Example:
x > 100
is a valid test. Ifx
is greater than 100, the result istrue
; otherwise, it’sfalse
. - The test is always placed inside round brackets
( )
immediately following theif
keyword.
- This must be a boolean expressionâan expression that evaluates to either
- The Guarded Instructions:
- These are placed inside the curly braces
{ }
. - They will only be executed if the test evaluates to
true
.
- These are placed inside the curly braces
- Program Flow:
- If the test is true, the instructions inside the
if
block run. - If the test is false, the
if
block is skipped, and the program continues with the next line after the closing brace.
- If the test is true, the instructions inside the
Everyday Examples of Boolean Expressions:
"This password is valid"
â could be represented in code asif (password.equals(correctPassword))
"There is an empty seat on the plane"
â might translate toif (availableSeats > 0)
"The temperature in the lab is too high"
â could beif (temperature > maxTempLimit)
Example in Code:
javaCopyEditif (age < 13) {
System.out.println("Hello Junior!");
}
System.out.println("Enjoy your ride");
In this example:
- The test
age < 13
is the condition. "Hello Junior!"
is only printed if the test returnstrue
.
Improved with Selection (if statement)
javaCopyEditimport java.util.*;
// This program is an example of the use of selection in a Java program
public class RollerCoaster2 {
public static void main(String[] args) {
int age;
Scanner keyboard = new Scanner(System.in);
System.out.println("How old are you?");
age = keyboard.nextInt();
if (age < 13) // test controls if the next instruction is executed
{
System.out.println("Hello Junior!");
}
System.out.println("Enjoy your ride");
}
}
đ Key Points:
- Condition:
if (age < 13)
evaluates whether the user is under 13. - Guarded Block:
"Hello Junior!"
is only printed if the condition is true. - Unconditional Message:
"Enjoy your ride"
is always displayed, regardless of age.
This small addition significantly improves how the program responds to different users, making it more dynamic and appropriate.
Now the message “Hello Junior!” will only be executed if the test (age<13) is true, otherwise it will be skipped in figure.

Understanding the if
Statement in Action
Let’s walk through how Program 3.2 behaves in two different scenariosâfirst with a child and then with an adultâand clarify how the if
statement affects the program flow.
đ§ Child Scenario (Age = 10):
sqlCopyEditHow old are you?
10
Hello Junior!
Enjoy your ride
- The user enters
10
. - The test
if (age < 13)
evaluates totrue
. - As a result, “Hello Junior!” is displayed.
- Then the program continues and “Enjoy your ride” is also displayed.
đ¨ Adult Scenario (Age = 45):
sqlCopyEditHow old are you?
45
Enjoy your ride
- The user enters
45
. - The test
if (age < 13)
evaluates tofalse
. - The line
System.out.println("Hello Junior!");
is skipped. - Only “Enjoy your ride” is displayed.
đ Important Notes on Syntax
Currently, the code looks like this:
javaCopyEditif (age < 13) {
System.out.println("Hello Junior!");
}
System.out.println("Enjoy your ride");
This version uses braces {}
, which is the recommended practice, even when guarding a single instruction. It ensures clarity and reduces the chance of bugs when modifying the code later.
â Optional Form (Without Braces):
If there’s only one instruction to guard, Java allows you to skip the braces:
javaCopyEditif (age < 13)
System.out.println("Hello Junior!");
System.out.println("Enjoy your ride");
However, be carefulâonly the first line after the if
is guarded. This version is more prone to errors, especially if more lines are added later assuming they’re still under the if
.
đ Best Practice:
Even though braces are optional for single-line if
blocks, it’s a good habit to always use them. It makes your code more readable and safer to edit in the future.
Comparison operators
In Java, comparison operators (also known as relational operators) are used to compare two values. These operators produce a boolean resultâeither true
or false
âwhich makes them ideal for use in if
statements and other control structures.
đ Table 3.1 â Java Comparison Operators
Operator | Meaning | Example | Description |
---|---|---|---|
== | Equal to | x == 10 | True if x is equal to 10 |
!= | Not equal to | x != 5 | True if x is not equal to 5 |
< | Less than | x < 20 | True if x is less than 20 |
> | Greater than | x > 100 | True if x is greater than 100 |
>= | Greater than or equal to | x >= 50 | True if x is 50 or more |
<= | Less than or equal to | x <= 12 | True if x is 12 or less |
â ď¸ Common Mistake: =
vs ==
=
is the assignment operator (used to assign values).==
is the equality comparison operator (used to compare values).
â Correct:
javaCopyEditif (angle == 90) {
System.out.println("This IS a right angle");
}
â Incorrect (and dangerous!):
javaCopyEditif (angle = 90) // This assigns 90 to angle, not compares!
This common mistake can lead to unexpected behavior or compiler errors.
â More Examples:
Checking for Hot Days:
javaCopyEditif (temperature >= 18) {
System.out.println("Today is a hot day!");
}
Checking if an Angle is NOT a Right Angle:
javaCopyEditif (angle != 90) {
System.out.println("This is NOT a right angle");
}
These examples show how comparison operators help your program make logical decisions.
Multiple instruction within an ‘if’ statement
When more than one instruction needs to be conditionally executed, you must use braces {}
to group them. Without braces, only the first line after the if
is treated as conditional, which can lead to logical errors.
â Example: Program 3.3 with Discount Logic
javaCopyEditimport java.util.*;
public class FindCostWithDiscount {
public static void main(String[] args) {
double price, tax;
Scanner keyboard = new Scanner(System.in);
System.out.println("*** Product Price Check ***");
System.out.print("Enter initial price: ");
price = keyboard.nextDouble();
System.out.print("Enter tax rate: ");
tax = keyboard.nextDouble();
// Selection using if statement for promotion
if (price > 100) {
System.out.println("Special Promotion: We pay half your tax!");
tax = tax * 0.5; // Apply discount
}
// This always runs
price = price * (1 + tax / 100);
System.out.println("Cost after tax = " + price);
}
}
đ§Ş Sample Runs:
đ¸ No Discount (price ⤠100):
mathematicaCopyEdit*** Product Price Check ***
Enter initial price: 20
Enter tax rate: 10
Cost after tax = 22.0
đš Discount Applied (price > 100):
yamlCopyEdit*** Product Price Check ***
Enter initial price: 1000
Enter tax rate: 10
Special Promotion: We pay half your tax!
Cost after tax = 1050.0
â ď¸ Why Braces Matter
If you removed the braces like this:
javaCopyEditif (price > 100)
System.out.println("Special Promotion: We pay half your tax!");
tax = tax * 0.5; // This line will ALWAYS run, even if price <= 100
The second line (tax = tax * 0.5
) would no longer be conditionalâit would run every time, which is incorrect behavior.
đ§ Summary
- Use
{}
when guarding multiple lines under anif
condition. - Without
{}
, only the next immediate line is considered part of theif
. - You can extend logic clearly and safely by consistently using braces.
The âifâŚelseâ statement
You’ve now seen how the if...else
statement in Java adds an essential improvement over the simple if
structure by allowing your program to choose between two distinct paths of execution. This type of control structure is called a double-branched selection.
đ Key Concept Recap: if...else
Statement
The structure:
javaCopyEditif (/* condition */) {
// Instructions if the condition is true
} else {
// Instructions if the condition is false
}
This ensures exactly one of the two blocks is executed depending on the result of the condition.
â Example: Program 3.4 â DisplayResult
javaCopyEditimport java.util.*;
public class DisplayResult {
public static void main(String[] args) {
int mark;
Scanner keyboard = new Scanner(System.in);
System.out.println("What exam mark did you get? ");
mark = keyboard.nextInt();
if (mark >= 40) {
System.out.println("Congratulations, you passed");
} else {
System.out.println("I'm sorry, but you failed");
}
System.out.println("Good luck with your other exams");
}
}
đ§Ş Sample Outputs
âď¸ Passing Grade:
csharpCopyEditWhat exam mark did you get?
52
Congratulations, you passed
Good luck with your other exams
â Failing Grade:
vbnetCopyEditWhat exam mark did you get?
35
I'm sorry, but you failed
Good luck with your other exams
đ§ Summary
- The
if
part handles one possibility (e.g., pass). - The
else
part handles the opposite (e.g., fail). - The rest of the program continues afterward regardless of the path taken.
This allows your program to respond dynamically to input and handle different situations clearly and effectively.
Logical operators
As weâve already discussed, the test in an if
statement is an expression that produces a boolean resultâeither true
or false
. Often, itâs necessary to combine two or more tests to create a more complex condition.
Example: Checking the Temperature in a Laboratory
Letâs consider a program that checks the temperature in a laboratory. For the experiments to be successful, the temperature must remain between 5 and 12 degrees Celsius. An if
statement can be used to check whether the temperature is within this range, as shown below:
javaCopy codeif (/* test to check if temperature is safe */) {
System.out.println("TEMPERATURE IS SAFE!");
} else {
System.out.println("UNSAFE: RAISE ALARM!!");
}
Combining Multiple Tests with Logical Operators
To determine whether the temperature is within the safe range, we need to combine two conditions:
- Check if the temperature is greater than or equal to 5 (
temperature >= 5
) - Check if the temperature is less than or equal to 12 (
temperature <= 12
)
For both conditions to be true, we can use the logical AND operator (&&
), which ensures that both conditions must be satisfied for the test to pass. The correct if
statement would be:
javaCopy codeif (temperature >= 5 && temperature <= 12) {
System.out.println("TEMPERATURE IS SAFE!");
} else {
System.out.println("UNSAFE: RAISE ALARM!!");
}
How the Logic Works:
- When the temperature is below 5: The first test (
temperature >= 5
) evaluates tofalse
. As a result, the overall test isfalse
, and theelse
branch is executed:UNSAFE: RAISE ALARM!!
. - When the temperature is greater than 12: The second part of the test (
temperature <= 12
) evaluates tofalse
, making the overall resultfalse
as well, and theelse
branch is executed again. - When the temperature is between 5 and 12: Both tests (
temperature >= 5
andtemperature <= 12
) aretrue
, so theif
statement is executed and the messageTEMPERATURE IS SAFE!
is printed.
Important Notes:
- Complete Specification: Each test must be fully specified. Itâs incorrect to write the following: javaCopy code
// Incorrect! Second test does not mention 'temperature' if (temperature >= 5 && <= 12)
This will cause a compilation error because the second condition (<= 12
) is incompleteâit doesnât mention the variabletemperature
.
Logical Operators in Java
Java provides several logical operators to combine or manipulate boolean expressions. Here are the most common ones:
Logical Operator | Java Symbol | Meaning | Result is true when⌠|
---|---|---|---|
AND | && | Both conditions must be true | Both conditions are true |
OR | ` | ` | |
NOT | ! | Negates a condition | Flips the value: true becomes false, and vice versa |
Examples of Logical Operators:
Expression | Result | Explanation |
---|---|---|
10 > 5 && 10 > 7 | true | Both conditions are true |
10 > 5 && 10 > 20 | false | The second condition is false |
10 > 15 && 10 > 20 | false | Both conditions are false |
`10 > 5 | 10 > 7` | |
`10 > 5 | 10 > 20` | |
`10 > 15 | 10 > 20` | |
!(10 > 5) | false | The original test is true, but NOT flips it |
!(10 > 15) | true | The original test is false, so NOT flips it |
Using the NOT
Operator:
Letâs revisit the temperature example where a temperature greater than 18 degrees is considered a hot day. To check if the day is not a hot day, we could use the NOT operator (!
):
javaCopy codeif (!(temperature > 18)) { // test if temperature is not hot
System.out.println("Today is not a hot day!");
}
Alternatively, we could achieve the same result without the NOT
operator by simply checking if the temperature is less than or equal to 18:
javaCopy codeif (temperature <= 18) { // checks if temperature is not hot
System.out.println("Today is not a hot day!");
}
Nested ‘if…else’ statements
In Java, instructions within if
and if...else
statements can themselves be any valid Java command, and importantly, they can also contain other if
or if...else
statements. This form of control is known as nesting, and it allows multiple conditions or choices to be evaluated and processed.
Example: Checking Tutorial Group and Lab Time
Consider the following program where a student is asked to enter their tutorial group (A, B, or C), and the program will display the corresponding lab time. The program uses nested if...else
statements to handle the different groups.
javaCopy codeimport java.util.*;
public class Timetable {
public static void main(String[] args) {
char group; // To store the tutorial group
Scanner keyboard = new Scanner(System.in);
System.out.println("***Lab Times***");
System.out.println("Enter your group (A, B, C)");
group = keyboard.next().charAt(0); // Capture the first character of the input
// Check tutorial group and display the appropriate lab time
if (group == 'A') {
System.out.print("10.00 a.m"); // Lab time for group A
} else {
if (group == 'B') {
System.out.print("1.00 p.m"); // Lab time for group B
} else {
if (group == 'C') {
System.out.print("11.00 a.m"); // Lab time for group C
} else {
System.out.print("No such group"); // Invalid group
}
}
}
}
}
Explanation of the Nested if...else
Statements:
- First
if
statement: Checks if the entered group is ‘A’. If it is, it prints the corresponding lab time for group A (10:00 a.m.). else
branch: If the group isn’t ‘A’, it checks if it’s ‘B’ in the secondif
statement. If true, it prints the lab time for group B (1:00 p.m.).- Nested
else if
: If the group isn’t ‘B’ either, it checks if it’s ‘C’ in the thirdif
statement. If true, it prints the lab time for group C (11:00 a.m.). - Final
else
statement: If the entered group is not ‘A’, ‘B’, or ‘C’, it prints an error message:"No such group"
.
Improving Readability with else if
While nesting can be useful, it often leads to code that’s difficult to read, especially when dealing with many conditions. To make the code more readable, Java provides an alternative to deeply nested if...else
statements: the else if
statement. This avoids the need for multiple levels of indentation and makes the logic clearer.
Hereâs how the same logic can be rewritten using else if
statements:
javaCopy codeif (group == 'A') {
System.out.print("10.00 a.m");
} else if (group == 'B') {
System.out.print("1.00 p.m");
} else if (group == 'C') {
System.out.print("11.00 a.m");
} else {
System.out.print("No such group");
}
Error Checking
In the examples above, error checking is an important feature. Weâre not assuming that the user will always enter a valid group (A, B, or C). If the user enters an invalid group, the program displays an error message: "No such group"
. This is an essential practice in programming, ensuring that your programs can handle unexpected inputs gracefully.
Limitations of Nested if...else
Statements
While nested if
statements work well for small numbers of options, they can become cumbersome and difficult to manage as the number of options increases. With a large number of choices, the code can quickly become messy and hard to read. Fortunately, Java offers an alternative control structure to handle such cases more efficiently: the switch
statement.
In conclusion, while nesting allows for multiple layers of conditional statements, using else if
improves readability by eliminating unnecessary levels of indentation. For larger, more complex decision trees, the switch
statement is often a better choice, which we’ll explore next.
The ‘switch’ statement
In Program 3.5, nested if...else
statements were used to determine the tutorial group’s lab time. However, Program 3.6 demonstrates the same functionality using a switch
statement, which results in cleaner, more readable code. Letâs take a closer look at this program.
Program 3.6: Timetable with switch
javaCopy codeimport java.util.*;
public class TimetableWithSwitch {
public static void main(String[] args) {
char group; // To store the tutorial group
Scanner keyboard = new Scanner(System.in);
System.out.println("***Lab Times***");
System.out.println("Enter your group (A, B, C)");
group = keyboard.next().charAt(0); // Capture the first character of the input
// Using the switch statement to check the group
switch(group) { // Beginning of the switch
case 'A':
System.out.print("10.00 a.m ");
break;
case 'B':
System.out.print("1.00 p.m ");
break;
case 'C':
System.out.print("11.00 a.m ");
break;
default:
System.out.print("No such group");
} // End of the switch
}
}
Explanation of the switch
Statement
The switch
statement simplifies the control flow when dealing with multiple possible values for a single variable, especially when the options are specific (such as checking for 'A'
, 'B'
, or 'C'
), rather than ranges of values.
How the switch
statement works:
- Variable to Test: The
switch
statement starts with the variable that is being tested. In this case, it’sgroup
, which contains the character representing the tutorial group entered by the user. - Case Labels: Each
case
represents a possible value for the variablegroup
.- If
group
is'A'
, the program executes the code in thecase 'A'
block: it prints"10.00 a.m "
. - Similarly, for
case 'B'
, it prints"1.00 p.m "
, and forcase 'C'
, it prints"11.00 a.m "
.
- If
break
Statements: After each block of code under acase
, abreak
statement is used. This ensures that once a matchingcase
is found, the program will stop checking the remaining cases and exit theswitch
statement. If abreak
is omitted, the program will continue executing the code in the subsequentcase
blocks (a behavior called “fall-through”).default
Case: Thedefault
case is optional but is commonly used to handle situations where none of the specifiedcases
match the variable. In this program, if the entered group is neither'A'
,'B'
, nor'C'
, thedefault
block prints"No such group"
.
Advantages of Using the switch
Statement
- Compactness and Readability: The
switch
statement eliminates the need for deeply nestedif...else
statements, making the code cleaner and more readable. - Efficiency: For large numbers of possible values, a
switch
statement is more efficient and straightforward than multipleif...else
branches.
General Syntax of a switch
Statement
The general structure of a switch
statement in Java is as follows:
javaCopy codeswitch (someVariable) {
case value1:
// instructions to execute if someVariable == value1
break;
case value2:
// instructions to execute if someVariable == value2
break;
// more cases can follow
default:
// instructions to execute if no case matches
}
- someVariable: The variable being tested (e.g.,
group
). - case value: Each
case
defines a specific value to match againstsomeVariable
. break
: Ensures that once a match is found, the program skips the remainingcases
.default
: An optional case to handle situations where no cases match.
Key Points to Remember
- Variable Type: The variable tested in a
switch
statement is usually of types likeint
,char
,long
,byte
, orshort
. In this case, itâs achar
type (group
). - Specific Values:
switch
is most effective when checking for specific values (like'A'
,'B'
, or'C'
), not ranges or complex conditions (such as>= 40
). break
Importance: Thebreak
statement is crucial to ensure that the program doesn’t continue executing subsequent cases after a match.default
Case: Itâs good practice to use thedefault
case to handle unexpected input or to serve as a fallback for unmatched values.
Comparison to Nested if...else
Using if...else
(from Program 3.5):
- More verbose and harder to maintain when there are many options.
- Increased indentation makes the code harder to read.
Using switch
(from Program 3.6):
- More concise and easier to maintain.
- Better suited for handling multiple specific conditions for a single variable.
Conclusion
The switch
statement provides a cleaner, more structured approach to handling multiple conditions that check for specific values. While nesting if...else
statements works well for small numbers of options, using a switch
statement improves readability and makes the code more efficient when checking for specific values.
Grouping case statements
In the case where multiple case
options should lead to the same block of instructions, the switch
statement in Java allows you to combine multiple case
labels before the block of code is executed. This eliminates the need to repeat the same code for each case
and can make your code more efficient and concise.
Program 3.7: Handling Multiple Cases with the Same Instructions
Let’s extend the previous example where both Group A and Group C have the same lab time, 10.00 a.m.. Initially, you could write the switch
statement like this:
javaCopy codeswitch(group) {
case 'A':
System.out.print("10.00 a.m ");
break;
case 'B':
System.out.print("1.00 p.m ");
break;
case 'C':
System.out.print("10.00 a.m ");
break;
default:
System.out.print("No such group");
}
This works correctly, but you are repeating the instruction System.out.print("10.00 a.m ");
for both Group A and Group C, which is redundant.
Refining the Code by Combining Case Labels
You can improve the code by combining case 'A'
and case 'C'
to eliminate redundancy. Here’s how you can do it:
javaCopy codeswitch(group) {
case 'A':
case 'C':
System.out.print("10.00 a.m ");
break;
case 'B':
System.out.print("1.00 p.m ");
break;
default:
System.out.print("No such group");
}
Explanation:
- Combining
case 'A'
andcase 'C'
: By placingcase 'A'
andcase 'C'
together without abreak
in between, you ensure that the same instruction (System.out.print("10.00 a.m ");
) is executed for both cases. - Why it works: Once the program enters
case 'A'
orcase 'C'
, the code inside theswitch
block executes without interruption, because there is nobreak
aftercase 'A'
. The program continues executing the same code forcase 'C'
as well, since they are grouped together. break
statement: After executing the shared instruction, thebreak
statement ensures that the program exits theswitch
statement and does not continue checking furthercase
labels.default
case: Thedefault
case remains unchanged and will be executed if the user enters any invalid group (not ‘A’, ‘B’, or ‘C’).
Benefits of Combining case
Labels:
- Efficiency: By combining cases, you avoid writing duplicate code. In the example above, both ‘A’ and ‘C’ lead to the same output without repeating the same print statement.
- Readability: The code becomes cleaner and more readable because it avoids redundancy and highlights the cases that share the same result.
- Flexibility: You can combine any number of
case
labels. This is helpful when multiple options should produce the same result.
Extended Example: More Combined Cases
Letâs extend this concept further. Assume that groups A, C, and D all have the same lab time. You can group all of them into one case
block:
javaCopy codeswitch(group) {
case 'A':
case 'C':
case 'D':
System.out.print("10.00 a.m ");
break;
case 'B':
System.out.print("1.00 p.m ");
break;
default:
System.out.print("No such group");
}
Here, Group A, Group C, and Group D all share the same lab time of 10.00 a.m., and the switch
statement handles all of them together efficiently.
Conclusion
In situations where multiple case
options lead to the same instructions, combining the case
labels before the block of code allows you to eliminate redundancy and improve the clarity and efficiency of your switch
statements.
Removing break statements
In the example provided (Program 3.7), we are dealing with a situation where multiple case
statements can be executed in a switch
block without needing a break
after each case. This allows you to “fall through” from one case to the next, which is useful when you want to execute multiple actions for a certain condition or a range of conditions.
Explaining the Fall-Through Behavior in Switch Statements
In most cases, a break
statement is used in a switch
statement to prevent the program from continuing to execute the code associated with subsequent case
labels. However, when you do not include a break
statement at the end of a case, Java will execute the code for that case and then “fall through” to the next case, continuing until a break
statement is encountered or the end of the switch
block is reached.
In Program 3.7, this is demonstrated with the security levels for secret agents:
Program 3.7 (Modified)
javaCopy codeimport java.util.*;
public class SecretAgents {
public static void main(String[] args) {
int security;
Scanner keyboard = new Scanner(System.in);
System.out.println("***Secret Agents***");
System.out.println("Enter security level (1,2,3)");
security = keyboard.nextInt();
switch(security) { // check level of security
case 3:
System.out.println("The code to access the safe is 007."); // level 3 security
case 2:
System.out.println("Jim Kitt is really a double agent."); // level 2 security
case 1:
System.out.println("Martinis in the hotel bar may be poisoned."); // level 1 security
break; // necessary to avoid error message below
default:
System.out.println("No such security level.");
}
}
}
How the Fall-Through Works
- When the security level is 3:
- The code in
case 3
is executed:System.out.println("The code to access the safe is 007.");
- There is no
break
aftercase 3
, so Java falls through tocase 2
and executes:System.out.println("Jim Kitt is really a double agent.");
- Since there is no
break
aftercase 2
, it then falls through tocase 1
and executes:System.out.println("Martinis in the hotel bar may be poisoned.");
- Finally, when the program reaches the
break
statement incase 1
, it exits theswitch
block.
- The code in
- When the security level is 2:
- The code in
case 2
is executed:System.out.println("Jim Kitt is really a double agent.");
- There is no
break
aftercase 2
, so it falls through tocase 1
and executes:System.out.println("Martinis in the hotel bar may be poisoned.");
- The
break
statement incase 1
exits theswitch
block.
- The code in
- When the security level is 1:
- The code in
case 1
is executed:System.out.println("Martinis in the hotel bar may be poisoned.");
- The
break
statement incase 1
exits theswitch
block.
- The code in
- When the security level is invalid (e.g., 8):
- The
default
case is executed:System.out.println("No such security level.");
- The
Sample Test Runs
- Security level 3: pgsqlCopy code
***Secret Agents*** Enter security level (1,2,3) 3 The code to access the safe is 007. Jim Kitt is really a double agent. Martinis in the hotel bar may be poisoned.
- Security level 2: pgsqlCopy code
***Secret Agents*** Enter security level (1,2,3) 2 Jim Kitt is really a double agent. Martinis in the hotel bar may be poisoned.
- Security level 1: markdownCopy code
***Secret Agents*** Enter security level (1,2,3) 1 Martinis in the hotel bar may be poisoned.
- Invalid security level (e.g., 8): pgsqlCopy code
***Secret Agents*** Enter security level (1,2,3) 8 No such security level.
Why Fall-Through Might Be Useful
The fall-through behavior is particularly useful when:
- You want to perform multiple actions for a range of values. For example, if different security levels unlock progressively more secrets, you can group the
case
statements accordingly without repeating code. - You have a hierarchy or progression where each level requires the execution of not only its own block but also the blocks associated with lower levels.
When Fall-Through Might Not Be Ideal
While fall-through can be useful, it can sometimes lead to unexpected behavior if the programmer is not careful. It’s important to ensure that you don’t unintentionally execute code for cases you didn’t intend to.
Avoiding Fall-Through (Using Break Statements)
If you do not want fall-through behavior, you should always use break
statements after each case
. The break
prevents the program from continuing to the next case once the current case has been processed.
Summary
- Fall-through in a
switch
statement happens when you don’t include abreak
after acase
. This allows the execution of the nextcase
block. - It’s useful for executing the same code for multiple cases, but you need to be mindful to avoid executing unintended cases.
- If you want to prevent fall-through, include a
break
statement after eachcase
.
Self-test questions
- Explain the difference between sequence and selection.
- When would it be appropriate to use
an if statement?
an ifâŚelse statement?
a switch statement? - Consider the following Java program, which is intended to display the cost of a cinema ticket.
Part of the code has been replaced by a comment:
import java.util.; public class SelectionQ3 { public static void main(String[] args) { double price = 10.00; int age; Scanner keyboard = new Scanner(System.in); System.out.print(“Enter your age: “); age = keyboard.nextInt(); // code to reduce ticket price for children goes here System.out.println(“Ticket price = ” + price); } } Replace the comment so that children under the age of 14 get half price tickets. - Consider the following program: import java.util.;
public class SelectionQ4
{
public static void main(String[] args)
{
int x;
Scanner keyboard = new Scanner(System.in);
System.out.print(“Enter a number: “);
x = keyboard.nextInt();
if (x > 10)
{
System.out.println(“Green”);
System.out.println(“Blue”);
}
System.out.println(“Red”);
}
}
What would be the output from this program if
a) the user entered 10 when prompted?
b) the user entered 20 when prompted?
c) the braces used in the if statement are removed, and the user enters 10 when prompted?
d) the braces used in the if statement are removed, and the user enters 20 when prompted? - Consider the following program:
import java.util.; public class SelectionQ5 { public static void main(String[] args) { int x; Scanner keyboard = new Scanner(System.in); System.out.print(“Enter a number: “); x = keyboard.nextInt(); if (x > 10) { System.out.println(“Green”); } else { System.out.println(“Blue”); } System.out.println(“Red”); } } What would be the output from this program if a) the user entered 10 when prompted? b) the user entered 20 when prompted? - Consider the following program: import java.util.;
public class SelectionQ6
{
public static void main(String[] args)
{
int x;
Scanner keyboard = new Scanner(System.in);
System.out.print(“Enter a number: “);
x = keyboard.nextInt();
switch (x)
{
case 1: case 2: System.out.println(“Green”); break;
case 3: case 4: case 5: System.out.println(“Blue”); break;
default: System.out.println(“numbers 1-5 only”);
}
System.out.println(“Red”);
}
}
What would be the output from this program if
a) the user entered 1 when prompted?
b) the user entered 2 when prompted?
c) the user entered 3 when prompted?
d) the user entered 10 when prompted?
d) the break statements were removed from the switch statement and the user entered 3
when prompted?
e) the default were removed from the switch statement and the user entered 10 when
prompted?
Programming Exercises
1. Design and implement a program that asks the user to enter two numbers and then displays the message âNUMBERS ARE EQUALâ, if the two numbers are equal and âNUMBERS ARE NOT EQUALâ, if they are not equal.
Hint : Don’t forget to use the double equals (==) to test for equality.
2. Adapt the program developed in the question above so that as well as checking if the two numbers are equal, the program will also display âFIRST NUMBER BIGGERâ if the first number is bigger than the second number and display âSECOND NUMBER BIGGERâ if the second number is bigger than the first.
3. Design and implement a program that asks the user to enter two numbers and then guess at the sum of those two numbers. If the user guesses correctly a congratulatory message is displayed, otherwise a commiseration message is displayed along with the correct answer.
4. Implement program 3.4 which processed an exam mark and then adapt the program so that marks of 70 or above are awarded a distinction rather than a pass.
5. Write a program to take an order for a computer system. The basic system costs 375.99. The user then has to choose from a 38 cm screen (costing 75.99) or a 43 cm screen (costing 99.99).The following extras are optional.
Item Price
DVD/CD Writer 65.99
Printer 125.00
The program should allow the user to select from these extras and then display the final cost of the order.
6 Consider a bank that offers four different types of account (âAâ, âBâ, âCâ and âXâ). The following table illustrates the annual rate of interest offered for each type of account.
Account Annual rate of interest
A 1.5%
B 2%
C 1.5%
X 5%
Design and implement a program that allows the user to enter an amount of money and a type of bank account, before displaying the amount of money that can be earned in one year as interest on that money for the given type of bank account. You should use the switch statement when implementing this program.
Hint: be careful to consider the case of the letters representing the bank accounts. You might want to restrict this to, say, just upper case. Or you could enhance your program by allowing the user to enter either lower case or upper case letters.
7. Consider the bank accounts discussed in exercise 6 again. Now assume that each type of bank account is associated with a minimum balance as given in the table below:
Account Minimum balance
A 250
B 1000
C 250
X 5000
Adapt the switch statement of the program in exercise 6 above so that the interest is
applied only if the amount of money entered satisfies the minimum balance requirement for the given account. If the amount of money is below the minimum balance for the given account an error message should be displayed.
***END OF THE TOPIC***