Understanding switch statement in Java

Logo of Java cup that looks beautiful
Switch is a conditional statement that checks if a given value matches any of the given values. The value which is to be matched is passed into the switch(value) and then checking is done in the . Let us look at a generalized example to better understand this.
    When you go to a bakery offering lot of eateries, to eat a chocolate pie, you keep searching for it rejecting every other food item that you encounter. When once, you got the chocolate pie, you will have it and return.

In a similar way, the control checks each and every case until the value matches any case value. When a case matches, the statements corresponding to that case are executed.

One important thing: Support for String in switch is introduced in Java 7

Let us look at the prototype.


switch(value)
{ // Switch start
case val1: statements_val1; break;
case val2: statements_val2; break;
default: statements;
} // Switch end

Note: value and val1, val2 must be of the same type.

Let me explain what is written. The value is to be matched with val1, val2 and so on. If value equals val1, then statements_val1 are executed. The break keyword is used to come out of the switch. This is essential because, it prevents statements in other cases from being executed. The control checks each and every case until a match is found. Once the match is found, the corresponding statements are executed and if break is written, control comes out of the switch without executing other statements. If value was not matched with any case, the default will be executed. Simply, it acts like else, but unlike else this need not be at last, you can put it where ever you want. Here is a program on switch statement.

Note: value is checked in order written, as you know.


import java.util.*;
class Calculations
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
      
        System.out.println("Enter two numbers");
      
        // Take two numbers as input
        int a=s.nextInt();
        int b=s.nextInt();

        System.out.println("Menu\n--------------");
        System.out.println("A-->Addtion");
        System.out.println("S-->Subtraction");
        System.out.println("M-->Multiplication");
        System.out.println("D-->Division");
        System.out.println("R-->Reminder");
      
        // Convert to lowercase, either upper or lower
        // is ok
        String st=s.next().toLowerCase();
      
        // Works from Java 1.7 only
        switch(st)
        {
            case "a": System.out.println(a+b); break;
            case "s": System.out.println(a-b); break;
            case "m": System.out.println(a*b); break;
            case "d": System.out.println(a/b); break;
            case "r": System.out.println(a%b); break;
            default:  System.out.println("Invalid choice");
        }
      
    }
}

In the above example, st is the value that is to be checked. If st matches with a then a+b is printed and the break lets the control come out of switch. The remaining cases aren't checked. Now, let us see, for a change, removing the break statements. What happens? Let me explain.

Consider, you have removed all of the break statements. Then,
If the user inputs a along with a+b, a-b,a*b,a/b,a%b and Invalid choice are also printed because, you haven't written the break statement and that those statements are assumed to be the statements of case a. Now, let us try placing the break in the case s only.


case "a": System.out.println(a+b);
case "s": System.out.println(a-b); break;

Here, if the user inputs a then a+b is printed and as there is no break in case a, a-b is also printed. Now, as there is a break here, control comes out of switch. If the user inputs s then only a-b is printed. If the user enters m, then a*b,a/b,a%b, Invalid choice are printed as there is no break. In a similar way, you can apply the switch statement for any data types. For me, switch statement seems to be a cleaner way over the if for value-checking based conditions.

Here is a graphical representation of control flow..

Understanding switch statement visually

Also, see the official switch statement tutorial. If I helped you in understanding this, please share it.

No comments: