Skip to content

SwitchCase

Chris Ward edited this page Oct 7, 2022 · 2 revisions

If you have several possibilities you are checking, then an if/then/else can get pretty complicated. Using a switch/case statement can clean this up a bit. Look at this example.

package examples.c_ifthen;

public class SwitchCase {
    public static void main(String[] args) {

        int value = 2;

        switch(value) {
            case 1: 
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            case 3:
                System.out.println("three");
                break;
            default:
                System.out.println("how should I know");
        }
    }
}

Considering that the value = 2, what will this print to the console? What if we change the value to 5?

Instead of if (value == something) we say switch(something) and then provide a case for every possibility we want to check for. Notice the colons? Looks kinda python like doesn't it. I agree, but that is how it works. You can put more than one line, or statement between the case conditions. See the break; in there? We need one of those with each case to tell Java we got our answer, break out of our switch now.

Last bit there is the default. If no case statement matches, we would end up in the default. If is wise to always put a default there to catch anything you were not expecting.

We used an int for our variable on purpose. We are mostly stuck with using an int. No floats or Strings. We can use something called an enum. We will talk about them later - they get a whole page, but if you want to check the examples, under /i_enums/SwitchSimpleEnum go right ahead.

Otherwise, lets look at functions

Clone this wiki locally