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.
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.
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
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.