Making Choices in javaMastering Selection in Java Programming: A Complete Guide for BeginnersMaking Choices in java

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:

  1. The Test (Condition):
    • This must be a boolean expression—an expression that evaluates to either true or false.
    • Example: x > 100 is a valid test. If x is greater than 100, the result is true; otherwise, it’s false.
    • The test is always placed inside round brackets ( ) immediately following the if keyword.
  2. The Guarded Instructions:
    • These are placed inside the curly braces { }.
    • They will only be executed if the test evaluates to true.
  3. 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.

Everyday Examples of Boolean Expressions:

  • "This password is valid" → could be represented in code as if (password.equals(correctPassword))
  • "There is an empty seat on the plane" → might translate to if (availableSeats > 0)
  • "The temperature in the lab is too high" → could be if (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 returns true.

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.

Figure: The if statement allows a choice to be made in programs

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 to true.
  • 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 to false.
  • 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

OperatorMeaningExampleDescription
==Equal tox == 10True if x is equal to 10
!=Not equal tox != 5True if x is not equal to 5
<Less thanx < 20True if x is less than 20
>Greater thanx > 100True if x is greater than 100
>=Greater than or equal tox >= 50True if x is 50 or more
<=Less than or equal tox <= 12True 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 an if condition.
  • Without {}, only the next immediate line is considered part of the if.
  • 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:

  1. Check if the temperature is greater than or equal to 5 (temperature >= 5)
  2. 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 to false. As a result, the overall test is false, and the else branch is executed: UNSAFE: RAISE ALARM!!.
  • When the temperature is greater than 12: The second part of the test (temperature <= 12) evaluates to false, making the overall result false as well, and the else branch is executed again.
  • When the temperature is between 5 and 12: Both tests (temperature >= 5 and temperature <= 12) are true, so the if statement is executed and the message TEMPERATURE 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 variable temperature.

Logical Operators in Java

Java provides several logical operators to combine or manipulate boolean expressions. Here are the most common ones:

Logical OperatorJava SymbolMeaningResult is true when…
AND&&Both conditions must be trueBoth conditions are true
OR``
NOT!Negates a conditionFlips the value: true becomes false, and vice versa

Examples of Logical Operators:

ExpressionResultExplanation
10 > 5 && 10 > 7trueBoth conditions are true
10 > 5 && 10 > 20falseThe second condition is false
10 > 15 && 10 > 20falseBoth conditions are false
`10 > 510 > 7`
`10 > 510 > 20`
`10 > 1510 > 20`
!(10 > 5)falseThe original test is true, but NOT flips it
!(10 > 15)trueThe 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:

  1. 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.).
  2. else branch: If the group isn’t ‘A’, it checks if it’s ‘B’ in the second if statement. If true, it prints the lab time for group B (1:00 p.m.).
  3. Nested else if: If the group isn’t ‘B’ either, it checks if it’s ‘C’ in the third if statement. If true, it prints the lab time for group C (11:00 a.m.).
  4. 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:

  1. Variable to Test: The switch statement starts with the variable that is being tested. In this case, it’s group, which contains the character representing the tutorial group entered by the user.
  2. Case Labels: Each case represents a possible value for the variable group.
    • If group is 'A', the program executes the code in the case 'A' block: it prints "10.00 a.m ".
    • Similarly, for case 'B', it prints "1.00 p.m ", and for case 'C', it prints "11.00 a.m ".
  3. break Statements: After each block of code under a case, a break statement is used. This ensures that once a matching case is found, the program will stop checking the remaining cases and exit the switch statement. If a break is omitted, the program will continue executing the code in the subsequent case blocks (a behavior called “fall-through”).
  4. default Case: The default case is optional but is commonly used to handle situations where none of the specified cases match the variable. In this program, if the entered group is neither 'A', 'B', nor 'C', the default block prints "No such group".

Advantages of Using the switch Statement

  • Compactness and Readability: The switch statement eliminates the need for deeply nested if...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 multiple if...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 against someVariable.
  • break: Ensures that once a match is found, the program skips the remaining cases.
  • default: An optional case to handle situations where no cases match.

Key Points to Remember

  1. Variable Type: The variable tested in a switch statement is usually of types like int, char, long, byte, or short. In this case, it’s a char type (group).
  2. Specific Values: switch is most effective when checking for specific values (like 'A', 'B', or 'C'), not ranges or complex conditions (such as >= 40).
  3. break Importance: The break statement is crucial to ensure that the program doesn’t continue executing subsequent cases after a match.
  4. default Case: It’s good practice to use the default 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' and case 'C': By placing case 'A' and case 'C' together without a break 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' or case 'C', the code inside the switch block executes without interruption, because there is no break after case 'A'. The program continues executing the same code for case 'C' as well, since they are grouped together.
  • break statement: After executing the shared instruction, the break statement ensures that the program exits the switch statement and does not continue checking further case labels.
  • default case: The default 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 after case 3, so Java falls through to case 2 and executes: System.out.println("Jim Kitt is really a double agent.");
    • Since there is no break after case 2, it then falls through to case 1 and executes: System.out.println("Martinis in the hotel bar may be poisoned.");
    • Finally, when the program reaches the break statement in case 1, it exits the switch block.
  • 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 after case 2, so it falls through to case 1 and executes: System.out.println("Martinis in the hotel bar may be poisoned.");
    • The break statement in case 1 exits the switch block.
  • 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 in case 1 exits the switch block.
  • When the security level is invalid (e.g., 8):
    • The default case is executed: System.out.println("No such security level.");

Sample Test Runs

  1. 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.
  2. 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.
  3. Security level 1: markdownCopy code***Secret Agents*** Enter security level (1,2,3) 1 Martinis in the hotel bar may be poisoned.
  4. 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 a break after a case. This allows the execution of the next case 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 each case.

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***

Leave a Comment

Your email address will not be published. Required fields are marked *