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.
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.
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:
2) Internally it uses the equals method to compare, which means, if you pass null it will throw java.lang.NullPointerException, so beware of that.
3) 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.
4) 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
If you like this article, and interested to learn more about String data structure in Java, check out these amazing articles:
- How to create String array from ArrayList in Java
- How to count Vowels and Consonants in Java String
- How to replace String in Java
- How to use Substring in Java
- How to use Regular Expression to Search in String
- How to Split String in Java
- How to convert String to Integer in Java
- Best way to Convert Numbers to String in Java
- How to search a character in Java String
- How to check if a String contains at least one number in Java
- ArrayList to String in Java
- 3 Ways to Read InputStream as String in Java
- How to remove whitespace form String in Java
- How to reverse String in Java
- Difference between StringBuilder and StringBuffer in Java
- How to Check if String is Empty in Java
- Difference between String and StringBuffer in Java
- How to convert array to String in Java
- Difference between String literal and String Object in Java
- How to convert Enum to String in Java
- Best way to compare String in Java
Before using String in Switch case, think twice. String is not type safe, which means if you are passing commands as String e.g. "start" and "stop", there is no way compiler can help you if you pass "strat", which is just a spelling mistake but easy to make and hard to debug. Method invocation will fail at runtime without much of debug info. Same is true for integers, if a method accpets an int parameter and valid values are just 1 and 2, there is no way compiler can verify that. If you have to deal with fixed, constant command you better use Enum, becasue you can easily declare your commands like START, STOP as enum constants and compiler will make your you pass only valid commands. Any invalid command will generate error in IDE as soon as you type, so no more runtime failure. Enum is powerful and it also allows you to switch based upon values. This example can easily be written using enum as follows
ReplyDeleteenum Commands {
START, STOP, REWIND, FORWARD, PAUSE, SHUTDOWN;
}
public void execute(Command cmd){
swith(cmd){
case START:
break;
.....
}
}
By the way, "switch" doesn't accept String constant (i.e. static final), so it's not a good idea. I prefer the Enum option or classic if-else block
ReplyDelete