?

Algorithms & Data Structures

Free Version

Upgrade subject to access all content

Easy

Understanding the Flow of a Switch Statement

ALGOR-PR9XHI

A switch statement is a programming construct for comparing a variable against a set of possible values, referred to as cases. When a matching case is found, code execution begins at that case and continues until program flow is interrupted (for example, by a break or return statement). Switch statements can use various primitive data types, along with their respective wrapper classes, as input.

You are provided with the following function, which includes a switch statement:

public int calculate(String op, int a, int b) {
    int result;
    switch(op) {
        case "ADD":
            result = a + b;
            break;
        case "REVERSE SUBTRACT":
            int temp = a;
            a = b;
            b = temp;
        case "SUBTRACT":
            result = a - b;
            break;
        case "SQUARE":
            b = a;
        case "MULTIPLY":
            result = a * b;
            break;
        case "DIVIDE":
            result = a / b;
            break;
        default:
            result = 0;
            break;
    }

    return result;
}