switch statement in java

PROBLEM

You wish to use the switch statement in Java. Below we will see a classic example converting a day number to day name. Let’s suppose we have an integer number that represents the day of the week. The number is from 1 to 7 and 1 goes for Monday and 7 for Sunday as shown in the table below.

Description
Day number
1
2
3
4
5
6
7
Day name
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

We need a program that given this number will print out the name of the day.

solution

The switch is mainly used when we have 3 or more conditions that we want to check. If we want to check for something only 2 different cases then a normal if-statement can do its job. In the case above will need to check 7 different numbers and decide the name of the day.

The switch statement is made up with different cases. In our case we need 7 and one default that will act as the else case. For example when a number is not in the range of 1 to 7 the default case will handle it and print a user friendly message.
Let’s see the code below that will use the switch on a int variable:
				
					package com.programmerabroad;

public class SwitchStatement {

    public static void main(String[] args) {

        int dayNumber = 3;

        switch (dayNumber) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Unrecognized day number. Please use 1 to 7");
        }
    }
}

				
			

The break is needed in every case because it stops the code from falling in the next case or the default case. In the example above, it enters the case 3, prints the text and then breaks out of the switch statement.

output

Correct! The output is Wednesday

switch-statement-java

conclusion

In this post we saw how to use the switch statement. I suggest you try to remove the break from the switch and see if it breaks, also you can use the switch on a String variable to achieve the opposite result.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x