Java for students logo
Need help with Java programming assignment? Get affordable Java homework help.

Switch statement

Switch statement helps simplifying multiple choices in a program. Let's start with the sample problem.

Problem. User enters month's number, then program tells month's name.

If-based solution

First, let's solve it using if statement.

import java.util.Scanner;

 

public class IfBasedSolution {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            System.out.print("Enter month's number: ");

            int monthNumber;

            monthNumber = in.nextInt();

            if (monthNumber == 1)

                  System.out.println("January");

            else if (monthNumber == 2)

                  System.out.println("February");

            else if (monthNumber == 3)

                  System.out.println("March");

            else if (monthNumber == 4)

                  System.out.println("April");

            else if (monthNumber == 5)

                  System.out.println("May");

            else if (monthNumber == 6)

                  System.out.println("June");

            else if (monthNumber == 7)

                  System.out.println("July");

            else if (monthNumber == 8)

                  System.out.println("August");

            else if (monthNumber == 9)

                  System.out.println("September");

            else if (monthNumber == 10)

                  System.out.println("October");

            else if (monthNumber == 11)

                  System.out.println("November");

            else if (monthNumber == 12)

                  System.out.println("December");

            else

                  System.out.println("Invalid month.");

      }

}

Enter month's number: 5

May

One can see excessive code repetition: all lines with if are almost the same, except for one number. From the viewpoint of coding style it's not good at all.

Switch-based solution

By using switch statement, one gets more compact and better styled code:

import java.util.Scanner;

 

public class SwitchBasedSolution {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            System.out.print("Enter month's number: ");

            int monthNumber;

            monthNumber = in.nextInt();

            switch (monthNumber) {

            case 1:

                  System.out.println("January");

                  break;

            case 2:

                  System.out.println("February");

                  break;

            case 3:

                  System.out.println("March");

                  break;

            case 4:

                  System.out.println("April");

                  break;

            case 5:

                  System.out.println("May");

                  break;

            case 6:

                  System.out.println("June");

                  break;

            case 7:

                  System.out.println("July");

                  break;

            case 8:

                  System.out.println("August");

                  break;

            case 9:

                  System.out.println("September");

                  break;

            case 10:

                  System.out.println("October");

                  break;

            case 11:

                  System.out.println("November");

                  break;

            case 12:

                  System.out.println("December");

                  break;

            default:

                  System.out.println("Invalid month.");

                  break;

            }

      }

}

Enter month's number: 5

May

It looks better, doesn't it? Now, let's explore how it all works.

Switch statement

You might have already guessed the syntax of the switch statement. Nevertheless let's check if you are right. The switch statement consists of following "bricks":

Brick
Explanation
switch (monthNumber) { Tells the switch statement a control variable and opens a switch block.
case 1: Defines a case. If (monthNumber == 1) case's body will be executed.

      System.out.println("January");

      break;

Case's body to execute. It most often ends with break keyword, which prevents from executing next case. Don't forget about it, or switch statement may behave in undesired way.

case 2:

      ...

case 8:

      ...

More cases.

default:

                  System.out.println("Invalid month.");

                  break;

Default case. It's being executed, if control variable don't match any case.
} Closes switch block.

Which types for control variables are allowed?

A switch works with int, char, byte and short primitive types, their non-primitive wrappers (Integer, Character, Byte and Short) and enumerated types (will be discussed later). So, basically, it works with integer numbers and characters only. You can't use strings and float numbers as control variables.

Are ranges and enumerations allowed?

Unfortunately not. Switch can make a decision based on a single value only. For instance, you can't tell

case 1, 2, 3, 4, 5:

but you can use "fall through" mechanism for small ranges or enumerations.

Fall through feature

Remember we told not to forget about break keyword to prevent execution of the next case? In special situations one can omit that recommendation. As an example we will create a program to tell number of days in a month by it's number (in non leap-year):

import java.util.Scanner;

 

public class NumberOfDays {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            System.out.print("Enter month's number: ");

            int monthNumber;

            monthNumber = in.nextInt();

            switch (monthNumber) {

            case 1:

            case 3:

            case 5:

            case 7:

            case 8:

            case 10:

            case 12:

                  System.out.println("Number of days: 31");

                  break;

            case 4:

            case 6:

            case 9:

            case 11:

                  System.out.println("Number of days: 30");

                  break;

            case 2:

                  System.out.println("Number of days: 28");

                  break;

            default:

                  System.out.println("Invalid month.");

                  break;

 

            }

      }

}

Enter month's number: 5

Number of days: 31

Be careful with this feature. If you use it in a real program, always add comments, so you and other people reading your code know, that you omitted break on purpose:

            case 9:

                  // doing something...

                  // fall through

It's all we want to tell about the switch statement at the moment, but you will meet with it once more, when we'll discuss enumerations.

If you'd like to run your own website, but don't know where to start, check this tutorial: how to set up a website. There you find tips of how to setup your website step by step. Starting from choosing a domain name and concluding with how to promote your project.

Partners

  • TheTop10BestWebhosting.com

    If you are looking to transfer your hosting to a new cheap web hosting provider, or if you are new to web hosting and need help on which web hosts to go for and who to avoid, TheTop10BestWebHosting.com provides easy to follow information, so you can be assured you choose the best web hosting company to suit your webhosting needs.