Switch Statement in Java

Switch statement in Java

Well, we now know about the if-else conditional statements. Here we are going to start one more type of conditional statement which are switch statement. Well, switch statements are usually a choice of use when we need to switch through different cases (choices) for some situations and evaluate some cases out of many.

If this confuses you, just understand that we have multiple choices here on the basis of some expression/variable, and we are going to execute the appropriate alternative out of all(according to the variable).

Switch statement in Java

Let’s understand the idea with the help of an example. Let’s say that you are creating a program for implementing different arithmetic operations. Now, we know that we have different arithmetic operators like +, -, *, / right? Just consider that it depends on the operator, that what operation are we going to perform. This is like if the user enters +, we are going to perform addition, and so on.

So, here we have different arithmetic operations to perform, and on the basis of what operator the user chooses, it is decided what code to run. In such cases, we are using switch case statements. By the way, this can be done using the if-else statements also. You can try a hands-on program the user enters an operator which is basically a character. Before we try our hands on the program, we should have a look at the syntax of the switch statement –

switch (expression){
case A: //some statements relevant to this case.
break;
case B: //some statements again relevant for this case.
break;
case C: // yet some more statements relevant for this case
break;
default: // this is the default code that would run if no case executes.
}

So, here the thing is that we are having different cases, and on the basis of expression, we are executing some cases. Like here in the example that we are going to consider, we are going to decide the arithmetic operation on the basis of the operator that the user enters. So, if the user enters +, we are supposed to run the case of addition. Now note that here the A, B, C, and so on are just some placeholders. We are supposed to write some constant there.

Note that variables are not allowed here. We are going to write something like +, -, *, / here. Also, there is some default case, which executes if no case executes, meaning that the expression did not match any case.

Here, you might have observed something, like the break is written at the end of every case, except the last default one(we can write there too). This break is a keyword, which is used to break out from the switch after executing that particular case. But what if we do not write break? Well, if some case executes and it does not have a break in the end, then it will move to the next case executing its code, even if it is not relevant. This will go on literally till either it finds a break statement in some case, or reach the end case(sometimes default).

This is like you have entered the operator +, and forgot to write break at the end of the case +, and just below is the case for subtraction, then the code for the subtraction will also be executed even if it is not relevant in this case.

One more thing is that we cannot duplicate the cases. We can have only one case for addition, and one for subtraction, for example, that’s it.

Let’s implement the program for understanding the switch statement –

import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char operator;
int number1, number2;
System.out.println(“Please enter the arithmetic operator: “);
operator = scanner.next().charAt(0);
System.out.println(“Please enter the first number: “);
number1 = scanner.nextInt();
System.out.println(“Please enter the second number: “);
number2 = scanner.nextInt();
switch(operator){
case ‘+’:
System.out.println(number1 + number2);
break;
case ‘-‘:
System.out.println(number1 – number2);
break;
case ‘*’:
System.out.println(number1 * number2);
break;
case ‘/’:
System.out.println(number1 / number2);
break;
default:
System.out.println(“Sorry… I don’t know about this operation”);
}
}
}

So, if you try running the above program, you first enter the operator, then the first operand(number), and the other operand, and then according to what operator you have entered, that particular case executes. Notice that green-colored line? I have highlighted that line because it might seem alien to you and you may be kind of crazy like heyyy… what is this now?

So I want to explain this. I had to get a character input from the user. So all I did was get a word as user input, and then get the first character from that word. But I am going to input only one character so I am going to get only that character. So, scanner.next() does take a word for you as user input, and then we are doing charAt(0), which is a method that returns the zeroth character here(because we have given zero as input).

So, now we successfully have a character here with us. The rest of the things are known to you now(at least they are not alien to you). So, we are asked to enter some arithmetic operator, so we put + for example, and then the first number as 12, and the other number as 23. we receive the output as 35.

So, from this, I hope that the basic concept of the switch statements. Now, just imagine that you forgot to add the break statement somewhere, let’s say you forgot everywhere. Now, let’s execute it again. All we need to do is just remove all the break statements from the cases. I am not pasting the code again. Just let’s discuss the output. Here is the output –

Please enter the arithmetic operator:
+
Please enter the first number:
34
Please enter the second number:
12
46
22
408
2
Sorry… I don’t know about this operation

So, we could see that we have all the addition, subtraction, multiplication, division, and the default case to execute. This is because we forgot to add the break, which helps us get out of the switch after executing the relevant case. Try putting a break statement only in the case of * now, and try giving + as an input operator.

You will find that the output comes out to be till multiplication. Since there, the break statement is encountered, we move out of the switch. Well, this is kind of an interesting concept here, which we can use in such situations. Another example might be that you want to give some choices to your user, like press 1 and we will do this, press 2 and we will do that, or something like this. In such cases too, a switch statement can be a choice for you. You just switch on the basis of what the number is entered by the user and write an appropriate number of cases as per your requirements

Now, sometimes we might forget to write the break statement somewhere, and end up messing up the whole output since it does not come as expected. So, we have something called an enhanced switch, which comes with a simplified syntax, and we can get rid of the break statements. We use case labels here. So, if the above program was to be converted to an enhanced switch, it would look something like this –

import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char operator;
int number1, number2;
System.out.println(“Please enter the first number: “);
number1 = scanner.nextInt();
System.out.println(“Please enter the arithmetic operator: “);
operator = scanner.next().charAt(0);
System.out.println(“Please enter the second number: “);
number2 = scanner.nextInt();
switch(operator){
case ‘+’ -> System.out.println(number1 + number2);
case ‘-‘ -> System.out.println(number1 – number2);
case ‘*’ -> System.out.println(number1 * number2);
case ‘/’ -> System.out.println(number1 / number2);
default -> System.out.println(“Sorry… operator not recognized”);
}

}
}

Have a look at how simple has the syntax become now, and it is now more readable, which is again an advantage. Also, we do not need to write the break anymore. Try to run this program, for different cases.