Java - Switch Statement with Examples | Conditional Statements

Previously, we studied about If-else and Nested if-else statements in Java, where we used to check each condition one by one, which used to be a very lengthy task and even sometimes messier too. Imagine the value of the variable we are checking in the If statement suddenly changes, then our whole program would be affected. Isn't it? Keeping in mind this thing, the urge to find an alternative to this grew. So that all this checking and matching, goes up in one blow only. Thus, decreasing the number of comparisons to be made, thus decreasing the time complexity. At this point, Switch statement was introduced.

Switch statement helps in testing a variable of a value, amongst a bunch of conditions in just a single execution only. Meaning, the value is compared to the all the cases, and if there is a match, then the associated block is executed. This is a better alternative of if-else statement as the rigid structure of Switch statement makes it very much easier to make the comparisons in a very less time and execute the associated block faster.

Syntax:
switch(expression){
case condition1:
       Statements...  ;
       break;
case condition2:
       Statements...  ;
       break;
case condition3:
       Statements...  ;
       break;
.
.
.
.
default:
       Statements...  ;
       break;
}

* Here the expression provided by us in the switch(expression), if the variable or the expression, that we want to compare, it goes from case 1 to the last case. Checking each condition. And as soon as the condition matches, the associated statements are executed and the break statement, takes the control out of the switch statement.

Break statement - As the name suggests it breaks the execution at whatever point, we want it to. It just skips all the code after it, and takes the control to out of the switch statement. Meaning, suppose condition1 matches the expression, then the statements in case 1 would be executed and when break is encountered, it will understand that now its time to end this loop or conditional statement. And it directly go to the ending bracket of switch. And execute the rest of statements there.

The default at the end of the switch case is optional, it is executed when neither of the cases match with the expression.

Important Points about Switch cases:

1. If we remove all the breaks, or any break statements from the syntax, then there would be no stopping point for that case. Meaning, that when the particular case would be matched, its statements would be printed as usual, but it will also keep on executing other below unmatched cases after the matched case. Untill another break statement encounters

Example:
import java.util.Scanner;
public class switchCase {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter day");
        int dayOfWeek = scan.nextInt();
        switch(dayOfWeek) {
        case 1:
            System.out.println("Monday");
            //break;
        case 2:
            System.out.println("Tuesday");
            //break;
        case 3:
            System.out.println("Wednesday");
            //break;
        case 4:
            System.out.println("Thursday");
            //break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 7:
            System.out.println("Sunday");
            break;
        default:
            System.out.println("Enter a valid day");
        }
        scan.close();

    }
}

OUTPUT
Enter day
2
Tuesday
Wednesday
Thursday
Friday

You might be noticing scan.close() statement after the ending bracket of switch block. This is to avoid memory leak in the program. As we cannot re-use a Scanner Object again. So its better to get rid of that as soon as we exhaust the input. And thus reclaiming the Scanner's memory.

2. If we want the output of a few cases be same, then we can only write the case and the colon(:). This would consider that case same as the next case.

Example:
import java.util.Scanner;
public class switchpractice2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter value of x");
        int x = scan.nextInt();
        switch(x) {
        case 1:
        case 2:
        case 3:
            System.out.println("4");
            break;
        case 4:
            System.out.println("10");
            break;
        case 5:
            System.out.println("32");
            break;
        case 6:
            System.out.println("5");
            break;
        case 7:
            System.out.println("32");
            break;
        default:
            System.out.println("Invalid");
        }
        scan.close();

    }
}
OUTPUT
Enter value of x
2
4
3. Nesting can also be done in Switch statements,i.e we can add another switch statement in one switch statement, but it only makes the code complex. So avoid such things.

4. We can check for characters as well as we checked for integers. Even some sort of special expressions including constant values, could be used as a switch expression or cases inside switch block. But if we use variable expressions like switch(a*b+c), this would be invalid.

5. Duplicate cases are not allowed in Switch.

6. There could be N-number of cases in switch block. There's no limit for them.



Program 1 :  Making a Calculator with Switch Statement
import java.util.Scanner;
public class CalculatorWithSwitch {

    public static void main(String[] args) {

        char operator;
        int number1number2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number1 and number2 : ");
     number1 = scanner.nextInt();
        number2 = scanner.nextInt();
        System.out.print("Enter operator (either +, -, * or /): ");
        operator = scanner.next().charAt(0);
        switch (operator) {
            case '+':
                System.out.print(number1+number2);
                break;
            case '-':
                 System.out.print(number1-number2);
                break;
            case '*':
                 System.out.print(number1*number2);
                break;
            case '/':
                 System.out.print((float)number1/number2);
                 break;
            default:
                 System.out.println("Invalid operator!");
                 break;
        }

    }
}

OUTPUT
Enter number1 and number2 : 12 13
Enter operator (either +, -, * or /): /
0.9230769

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post