String item = "fruit"; if (item.equals("vegetable")) { System.out.println("Sorry, we are out of vegetables"); } else if (item.equals("fruit")) { System.out.println("What fruit do you want?"); } else { System.out.println("We don't have that item."); }So depending on the value of the variable item, we want to perform different type of codes. For now, we just have different String to output to the screen. But later in our program, this could be anything. Like if one if is satisfied, we could read contents from a file, if another value then maybe upload something to an FTP server! But to not complicate our example, let's just have different SysOut Strings. As seen above
Naturally, our code will match the second statement, hence the below expected output:
What fruit do you want?
The good thing is starting Java 7, switch statement involving String values are allowed. Hence, we could transform the code above to the code below:
String item = "fruit"; switch (item) { case "vegetable": System.out.println("Sorry, we are out of vegetables"); break; case "fruit": System.out.println("What fruit do you want?"); break; default: System.out.println("We don't have that item."); }The code now is easier to understand because the structure is better and simpler. We expect it to have better performance too. But for those who are still confused, here is what it does?
What fruit do you want?Note that the break statement is very important as it exits the switch statement. if we omit this, then the matching will just continue to go. For example, if we run the code below:
String item = "fruit"; switch (item) { case "vegetable": System.out.println("Sorry, we are out of vegetables"); case "fruit": System.out.println("What fruit do you want?"); default: System.out.println("We don't have that item."); }After matching the second value, it execute it's block and then continues to the next, which will result to executing the default section too. Hence we get the below output:
What fruit do you want? We don't have that item.
And if the first item was matched, like shown below:
String item = "vegetable"; switch (item) { case "vegetable": System.out.println("Sorry, we are out of vegetables"); case "fruit": System.out.println("What fruit do you want?"); default: System.out.println("We don't have that item."); }It will execute all the cases as it matched the first one. Which is not good if it is not what we intended it to do.
Sorry, we are out of vegetables What fruit do you want? We don't have that item.