KnowledgeBoat Logo

Conditional Statements in Java

Nested switch & Differences Between if and switch

ICSE Computer Applications


You can use switch statement as target of case to create nested switch statements. Here is an example of nested switch.

public class KboatNestedSwitch
{
    public void demoNestedSwitch() {

        int i = 0, j = 1;

        switch (i) {
            case 0:
                switch(j) {
                    case 0:
                        System.out.println("i is 0, j is 0");
                        break;
    
                    case 1:
                        System.out.println("i is 0, j is 1");
                        break;
    
                    default:
                        System.out.println("nested default case");
                        break;
                }
                break;

            case 1:
                System.out.println("i is 1");
                break;

            default:
                System.out.println("No matching case found");
                break;
        }
    }
}

The target of case 0 is another switch statement. Notice that the case constants in the inner switch and the outer switch are the same. This is valid. Switch statement defines its own block marked by its pairs of opening and closing curly braces. Because of this no conflict arises between the case constants in the inner switch and those in the outer switch. Below is the output of the program:

BlueJ output of Java program showing nested switch

Differences Between if & switch

We will complete our discussion of switch statements by looking at how it differs from if statement:

Differences Between if and switch statement in Java
  • switch can only test if the expression is equal to any of its case constants whereas if can test for any Boolean expression like less than, greater than, not equal to and so on
  • switch statement tests the same expression against a set of constant values whereas if-else-if ladder construct can use different expression involving unrelated variables.
  • The expression of switch statement must only evaluate to byte, short, int, char, String or an enum. So, we cannot test long and floating-point expressions using switch. if statement doesn’t have such limitations.
  • This last point will make up for all the limitations of switch we discussed in the above points. It is about performance. If you need to select from a very large group of values, a switch statement will run much faster than the equivalent program written using the if-else-if ladder. By putting all these constraints on switch, the compiler performs some very cool optimizations making it faster than if-else. Compiler optimization is an advanced topic so I will leave it at this only for this course.
PrevNext