How to use String literals in switch case in Java? Example Tutorial (original) (raw)
Switch Statements are not new for any Programmer, it is available in C, C++, Java and in all major programming language. The switch statement in Java allows you to a clear, concise, and efficient multiple-branch statement without lots and lots of messy if-else statements. But Java Switch and case statement have a limitation, you cannot use String in them. Since String is one of the most used classes in Java, and almost every program, starting from Hello World to a complex multi-tier Java application uses them, it makes a lot of sense to allow them in the Switch case. In Java 6 and before, the values for the cases could only be constants of integral type e.g. byte, char, short, int, and enum constants. If you consider Autoboxing then you can also use the corresponding wrapper class like Byte, Character, Short, and Integer.
From Java 1.7, language has been extended to allow String type in switch and case statement as well. This makes, Java programmer's life a bit easier, as it no more has to map String to Integers, to use them inside switch constructs.
In this Java 1.7 tutorial, we will learn How to use Strings in switch in Java. Like many Project Coin enhancements, e.g. underscore in numeric literals, Automatic resource management, this is really a very simple change to make life in Java 7 easier.
This is not a JVM level change, instead it is implemented as syntactic sugar. In all other respects, the switch statement remains the same, and internally it uses equals and hashcode method to make it work.
Java Program to use String in Switch Statement
In our example of using Strings in Switch case, we are accepting a String command from console, and passing it to our execute method, which is like a remote control, execute the command given. If you look at the code, we have used String variables in switch as well as case. They don't have to be upper case, but they are case sensitive, and that's why keeping them in one case, preferably upper case is good for maintenance.
import java.util.Scanner;
public class StringInSwitch{
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.println("Please enter command : ");
String command = scnr.nextLine();
// command = command.toUpperCase();
execute(command);
}
}
public static void execute(String command) {
switch (command) {
case "START":
System.out.println("Starting ...");
break;
case "STOP":
System.out.println("Stopping ...");
break;
case "REWIND":
System.out.println("Rewinding ...");
break;
case "FORWARD":
System.out.println("Forwarding ...");
break;
case "PAUSE":
System.out.println("Pausing ...");
break;
case "SHUTDOWN":
System.out.println("Shutting down ..");
System.exit(0);
break;
default :
System.out.println("Unknown Command");
}
}
}
Output : Please enter command : Start Unknown Command
Please enter command : START Starting ...
Please enter command : STop Unknonwn Command
Please enter command : STOP Stopping ...
Please enter command : SHUTDOWN Shutting down ..
From output, you can see that Strings in Switch statements are case sensitive. When we enter Start, it says unknown command, but when we entered START, it executes that command. That's why you should always convert user command into the either UPPER case or LOWER case, as required by your program, commented in our code for demonstration only.
Important things about Using String in Switch Statements
Here are a couple of important points about using String literal in switch statement feature in Java:
Strings in Switch are syntactic sugar, no change in JVM level.
Internally it uses the equals method to compare, which means, if you pass null it will throw java.lang.NullPointerException, so beware of that.
Strings in switch statements are case sensitive, prefer to use only one case and convert the input to the preferred case before passing them to switch statement.
The Java compiler generates generally more efficient byte code from switch statements that use String objects than from chained if-then-else statements. So prefer Strings with switch than nested if-else.
That's all folks on using String in Switch statement in Java. This feature is available from Java 7 and you are free to use them but write robust code, which can sustain Strings case sensitivity issue. By the way switch statements have changed a lot in recent Java version with new Switch expressions which also allows you to add options in switch statements like shown below. You can learn more about switch expression on my earlier article