switch statement in Java
March 24, 2020
If you would like to get rid of multiple nested else-if checks, then switch is the right way to go. In this post we will go through basic syntax and explain some moments you should keep an eye on while implementing it
Let’s suppose a user has typed a command to perform and it is stored in a String type variable called “input”. Now, based on the command was typed, we need to perform some actions.
Using if, else-if it can be done in the following manner:
String input = "add";
if(input.equals("remove")) {
System.out.println("You have requested to remove an item");
}
else if(input.equals("list")) {
System.out.println("You have requested to list all items");
}
else if(input.equals("add")) {
System.out.println("You have requested to add an item");
}
else{
System.out.println("Command was not recognized");
}
Well, this example definitely works, but it is not the best way how to handle such things, as it does not provide the visibility over available options and also amount of code is quite big.
Let’s look now how using switch statement we can adjust out example code
String input = "add";
switch(input) {
case "remove":
System.out.println("You have requested to remove an item");
break;
case "list":
System.out.println("You have requested to list all items");
break;
case "add":
System.out.println("You have requested to add an item");
break;
default:
System.out.println("Command was not recognized");
}
As you can see, available options are better organized which increases the visibility. Few moments to keep in mind:
– after case keyword you should provide the value against which you compare the variable. In the example these are remove, add, list
– break command is mandatory to be used, otherwise Java will not know where the code part related to a particular case stops and will execute all the following code until it reaches the end of switch statement or finds a break
– default keyword serves the same purpose as else keyword in if and specifies the code which should be executed of no match found. Like with else, default is optional and could be ommited.
Hopefully this post will be useful for you and now switch usage in Java is clear for you