Monday, August 15, 2022

How to use String literals in switch case in Java? Example Tutorial

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

How to use String in Swith in Java 7Here are a couple of important points about using String literal in switch statement feature in Java:


1) Strings in Switch are syntactic sugar, no change in JVM level.

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

how to use switch expression in Java




If you like this article, and interested to learn more about String data structure in Java, check out these amazing articles:

2 comments:

  1. 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

    enum Commands {
    START, STOP, REWIND, FORWARD, PAUSE, SHUTDOWN;
    }

    public void execute(Command cmd){
    swith(cmd){
    case START:
    break;
    .....
    }

    }

    ReplyDelete
  2. 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

Feel free to comment, ask questions if you have any doubt.