Switch Statements are not new for any Programmer, it is available in C, C++, Java and in all major programming language. Switch statement in Java allows you to a clear, concise and efficient multiple-branch statement without lots and lots of messy if-else statement. But Java Switch and case statement has limitation, you cannot use
String in them. Since String is one of the most used class in Java, and almost every program, starting from
Hello World to complex multi-tier Java application uses them, it makes lot of sense to allow them in 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 corresponding wrapper class e.g.
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 programmers 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.