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"); 
break; 
case 2: System.out.print("February"); 
break; 
case 3: System.out.print("March"); 
break; 
case 4: System.out.print("April"); 
break; 
case 5: System.out.print("May"); 
break; 
case 6: System.out.print("June"); 
break; 
case 7: System.out.print("July"); 
break; 
case 8: System.out.print("August"); 
break; 
case 9: System.out.print("September"); 
break; 
case 10: System.out.print("October"); 
break; 
case 11: System.out.print("November"); 
break; 
case 12: System.out.print("December"); 
break; 
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...
I am Prateek Singh and I have been coding and learning The Art of Programming for a while. I have been learning Java and a lot of languages by myself and I thought it would be great to share with those who too want to master this ART. Here, at Programmics, I will be sharing what I learned about this great ART and it will be great to learn together.
Posts created 13

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
Share via
Copy link