Java. The selection operator ‘switch’




The selection operator ‘switch’. Nested ‘switch’ statements


Contents


Search other websites:

1. What purpose does the ‘switch’ operator have in the programs?

The ‘switch’ operator is close to the conditional if-else statement. It allows you to organize the branching of the execution process in the program. In some cases, the use of the ‘switch’ operator gives a more compact program code than the conditional if-else statement.

 

2. What is the general form of the ‘switch’ statement?

In C-oriented programming languages, to which Java belongs, the ‘switch’ operator has the same general form of representation:

switch (expression)
{
    case value1:
        // statements
        ...
    break;
    case value2:
        // statements
        ...
    break;

    ...

    case valueN:
        // statements
        ...
    break;
    default:
        // operators that are executed by default
        ...
}

where

  • expression – a control expression that can have one of integer types: byte, int, short, char, or enumeration type. In new versions of JDK, the expression can be of type String.
  • value1, value2, …, valueN – constant expressions (literal values). Each value must be type-compatible with the specified expression.

The ‘default’ block can be absent.

 

3. The principle of operation of the switch statement

The operator of choice ‘switch’ works according to the following principle. The value of the expression is compared with any of the values (value1, value2, …, valueN) that follow after the keyword ‘case’. If a match is found, then the operators that follow this part of the ‘case’ statement are executed. If no match is found after “case”, then the operators that are in the “default” block are executed. If the ‘default’ block is missing (the block may be missing), then nothing happens and the next statement that follows the ‘switch’ statement is executed.

The ‘break’ statement is required to immediately exit the ‘switch’ statement. If the ‘break’ statement is executed, then the operator following the ‘switch’ is executed.

 



4. An example of using the switch operator, which has a default block

For a given value of n = 1..7 display the name of the corresponding day of the week. It is needed to consider the possible error values of n.

// the selection operator 'switch'
int n;
String s;

// input of the value n
n = 6;

switch (n)
{
    case 1:
        s = "Sunday";
    break;
    case 2:
        s = "Monday";
    break;
    case 3:
        s = "Tuesday";
    break;
    case 4:
        s = "Wednesday";
    break;
    case 5:
        s = "Thursday";
    break;
    case 6:
        s = "Friday";
    break;
    case 7:
        s = "Saturday";
    break;
    default:
        s = "Invalid day";
}

System.out.println(s);

 

5. An example of using the operator ‘switch’, in which the operators ‘break’ are absent

As you know, the break statement can be absent.

In this example, according to the entered day number value n = 1..7, the day off or work day is determined.

// the selection operator 'switch'
int n;
String s;

// ввод значения n
n = 3;

switch (n)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        s = "Working day";
    break;
    case 6:
    case 7:
        s = "Day off";
    break;
    default:
        s = "Invalid day";
}

System.out.println(s);

 

6. An example of using the operator ‘switch’, in which there is no block ‘default’

Given an integer n = 1..3. For a given value of variable n to determine:

  1. circumference;
  2. area of a circle;
  3. volume of a sphere.
// the selection operator 'switch'
int n;
double pi = 3.1415;
double r;

// input of the values n, r
// ...

switch (n)
{
    case 1:
        double d = 2*pi*r;
        System.out.println("Circumference = " + d);
    break;
    case 2:
        double s = pi*r*r;
        System.out.println("Area of a circle = " + s);
    break;
    case 3:
        double v = 4.0/3.0 * pi*r*r*r;
        System.out.println("Volume of a sphere = " + v);
    break;
}





 

7. Nested ‘switch’ statements. An example

The ‘switch’ statement can contain another, nested ‘switch’ statement. Each ‘switch’ statement defines its own code block. Blocks of code are independent of each other.

Example. In this example, based on the year and month numbers, the number of days in a month (variable days) is calculated. The task is solved using nested if and switch statements

// calculation of the number of days in the month of the year
int f;
int year;
int month;
int days;

// given month and year
year = 2404;
month = 2;

switch(month) {
    case 4: case 6: case 9: case 11:
        days = 30;
        break;
    case 2: // February
        f = 0; 

        // nested if statement
        if (year%400==0) f=1;
        else
        if (year%100==0) f=0;
        else
        if (year%4==0) f=1;

        // nested switch statement
        switch (f) {
            case 0:
                days=28;
                break;
            default:
                days=29;
        }
        break;
    default:
        days = 31; 
} 
System.out.println("Days = " + days);

 

8. Advantages of the switch statement in comparison with the if statement

In comparison with the if statement, the advantages of the switch statement are as follows:

  • when choosing from a large group of values, the switch statement is more faster than the if-else statement. This is due to the fact that in the switch statement the constants of all branches of the case and the expression are of the same type. Therefore, it is sufficient to carry out a test for equality. In the if-else statement, the compiler obviously does not know the types of the results of expressions in different branches of the comparison, which requires additional transformations that take time.
  • in cases when the code is executed for several statements of case branches without specifying the break statements separating them.

 

9. Disadvantages of the switch statement in comparison with the if statement

In comparison with the if statement, the switch statement has the following disadvantages:

  • in the switch statement, only equality is checked in each branch (matching search in the case branch). In the if statement in each branch, any logical expression of any type can be calculated;
  • in a switch statement, an expression that can be compared can only be of type int, an enumeration enum or a type of String (starting with JDK 7). The expression cannot be a floating point type. In the if statement, the compared expression can be of any type;
  • in two different branches of the case, the constants cannot have the same value. Same values in case branches are allowed only when these branches are placed at different levels of nesting in the case of nested switch statements.

 


Related topics