Switch Case in Java - Programmics! - Programmics! - We Love to Code.
demo image

Switch Case in Java - Programmics!

Share This
The Switch Case or The Switch Statements are used when we need to compare multiple conditions in a single program.
Switch Case in Java. - Programmics!


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 which 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!





No comments:

Post a Comment