Switch Case in Java

Another decision making statement is switch case. In switch case, some expression is evaluated and may appear different cases. So it executes code according to its case.

As the name says, first we switch to some variable or expression and write the codes for different cases. When the program executes, it executes the code according to the case value. It is same as if statements and used when we may have many results. Syntax:

switch(varibale or expression) {
    case value:
        statements goes here
        break;
    case value2:
        statements2 goes here
        break;
    default:
        default statement
}
As you can see above, first with switch keyword, we choosed variable. Then wrapped in curly braces, we wrote the code for every possible cases.
Note that we have to keep break after each cases' statement because if we don't, it will execute all code afterwards matching case. That means if we have 5 cases and we dont have break in between, after maching 3rd case it will also execute 4th and 5th case. But we dont need break for last statement as it doesnot have code afterwards.
We will learn more about break and continue later.


Examples:

We will give a number and this program will tell us which day it is in a week.
Code:

public class LearnSwitchCase { public static void main(String[] args) { int day = 3; switch(day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("Invalid number!"); } } }
Output:
Tuesday


We will check if given number is divisible by 3 or not.
Code:

public class LearnSwitchCase { public static void main(String[] args) { int day = 9; switch(day % 3) { case 0: System.out.println("It is divisible by 3."); break; default: System.out.println("It is not divisible by 3."); } } }
Output:
It is divisible by 3.


This program will say us how our grade is.
Code:

public class LearnSwitchCase { public static void main(String[] args) { char grade = 'B'; switch(grade) { case 'A': System.out.println("Excellent"); break; case 'B': System.out.println("Good"); break; case 'C': System.out.println("Average"); break; default: System.out.println("Try again"); } } }
Output:
Good


If Else If Statement in Java Previous Next Loops in Java