How To Use Switch Statement In Android/Java?

In this tutorial, we’re going to explore how to use the Switch statement in developing Android apps using Java. We’re not going to use Android Studio for this purpose. We’re going to use IntelliJ IDEA. However, the same code works on Android Studio. No issues at all! First of all, let’s see what actually a Switch statement is.

What is a Switch Statement?

A switch statement simply takes up a variable and matches its value against a number of values called cases. A switch statement checks if supplied variable is equal to a list of values. This function of the switch statement can also be achieved by If…else statement but using Switch-Case makes the whole process damn easier.

Syntax

switch(index){
    case 0:
        //Do this and this        break;
    case 1:
        //Do this and this        break;
    case 2:
        //Do this and this:        break;
    default: //For all other cases, do this        break;
}

where index is the variable whose value is matched. Since it’s an int, we match it with 0, 1, 2 and so on.

Example & Explanation

To understand the concept better, we take this small example:

public class Main {

    public static void main(String[] args) {
        String day;
        switch (day){
            case "Friday":
                //Woohoo, it's weekend time
                break;
            case "Saturday":
                //Rest time is now
                break;
            case "Sunday":
                //The day everyone waits for :)
                break;
            default: //Oh no, it's working day
                     //This code is executed when value of variable 'day'
                     //doesn't match with any of case above
                break;
        }
    }
}
Here let’s suppose a string variable ‘day’ holds the value of the current day whether it’s Monday, Tuesday and so on. We pass the value of ‘day’ at some point in the program. When switch statement is reached by the compiler, first of all, it compares the value of day with Friday. If matched, the code just before the break statement and after the case statement is executed. If the value isn’t matched, next case statement is reached. Now the value of the day is compared to Saturday.

The same process goes on until a case is matched and break statement is reached. If none of the cases is matched, code after default: is executed. Please note that break statement is optional. However, you should consider using it because once a case is matched and break statement is reached, compiler skips rest of switch section. If you don’t use the break statement, it will still keep matching with other cases.

Related posts