Java Program to Demonstrate Switch Case

This Java program is used to show the use of switch case to display the month based on the number assigned.

Example:
class monthno {
 public static void main(String argu[]) {
  int mnth = 6;
  switch (mnth) {
   case 1:
    System.out.println("Showing Month: January");
    break;
   case 2:
    System.out.println("Showing Month: February");
    break;
   case 3:
    System.out.println("Showing Month: March");
    break;
   case 4:
    System.out.println("Showing Month: April");
    break;
   case 5:
    System.out.println("Showing Month: May");
    break;
   case 6:
    System.out.println("Showing Month: June");
    break;
   case 7:
    System.out.println("Showing Month: July");
    break;
   case 8:
    System.out.println("Showing Month: August");
    break;
   case 9:
    System.out.println("Showing Month: September");
    break;
   case 10:
    System.out.println("Showing Month: October");
    break;
   case 11:
    System.out.println("Showing Month: November");
    break;
   case 12:
    System.out.println("Showing Month: December");
    break;
   default:
    System.out.println("Invalid input - Wrong month number.");
    break;
  }
 }
}

Explanation:
Here in this program, a Java class name monthno is declared which is having the main() method. All Java program needs one main() function from where it starts executing program. Inside the main(), the integer type variable name mnth is declared and initialized with value 6. This integer type variable will indicate to the month for which the case value is set.

Here inside the switch statement parenthesis the variable mnth is passed. Then, inside the switch block the cases are defined where case 1 will print " Showing Month: January" using the System.out.println() method. Similarly the case 2 will print " Showing Month: February" using the System.out.println() method and this will go on till case 12 will print " Showing Month: December" using the System.out.println() method.

After that according to the switch case structure, a default statement can be put which will get displayed an error message as wrong month number will get entered other than 1 till 12.


Here are few other related articles for you to read:

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.