Switch Case in Java.

What is Switch Case?

Switch Case or Switch Statements are used when we need to compare multiple conditions in a single program.

Switch case in java

The switch control structure has a switch expression, which stores a value. This value is now compared with different cases stored with a unique label.

Every label has some block of statements associated with it. If the value stored gets matched to the label of a particular case, the block of statement associated with it gets executed.

You must be thinking, what if none of the cases gets matched to the labels? Well, in that case, there is a label called default which gets executed if none of the labels get matched to the stored value.

Let’s have a look at this sample program to have a better understanding of the switch case –

import java.io.*;
class Month 
public static void main(String args[])
int mon=10; 
switch (mon)
case 1: System.out.print("January"); 
case 2: System.out.print("February"); 
case 3: System.out.print("March"); 
case 4: System.out.print("April"); 
case 5: System.out.print("May"); 
case 6: System.out.print("June"); 
case 7: System.out.print("July"); 
case 8: System.out.print("August"); 
case 9: System.out.print("September"); 
case 10: System.out.print("October"); 
case 11: System.out.print("November"); 
case 12: System.out.print("December"); 
default: System.out.print("You sure entered a number between 1 to 12"); break; 
} } }

Break Statement

Break Statement is the statement that is used to bring the control out of the switch expression.

The break statement should be written with every single case else the program will continue to execute every single statement written with the other labels.

Your Turn!

Now it’s your turn, to try this out!

Here are some programs you can practice on your own to improve your programming skills.

  1. Write a program in Java to accept an alphabet from the user and check whether it’s a vowel or a consonant.
  2. Write a program in Java to enter a year and check whether it’s a leap year or not.

Try these programs out and if stuck, I am always here to help you out.

Thanks for being here!

– Prateek Singh

Rating: 4.7/5. From 3 votes.
Please wait...


Please enter your comment!
Please enter your name here