Java Switch Case
Java switch case is a neat way to code for conditional flow, just like if-else conditions. Before Java 7, the only means to achieve string based conditional flow was using if-else conditions. But Java 7 has improved the switch case to support String also.
Java switch case String Example
Here I am providing a java program that shows the use of String in java switch case statements. For comparison, I am also providing another method which does the same conditional flow using if-else conditions.
SwitchStringExample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.journaldev.util; public class SwitchStringExample { public static void main(String[] args) { printColorUsingSwitch("red"); printColorUsingIf("red"); // switch case string is case sensitive printColorUsingSwitch("RED"); printColorUsingSwitch(null); } private static void printColorUsingIf(String color) { if (color.equals("blue")) { System.out.println("BLUE"); } else if (color.equals("red")) { System.out.println("RED"); } else { System.out.println("INVALID COLOR CODE"); } } private static void printColorUsingSwitch(String color) { switch (color) { case "blue": System.out.println("BLUE"); break; case "red": System.out.println("RED"); break; default: System.out.println("INVALID COLOR CODE"); } } } |
Here is the output of the above program.
1 2 3 4 5 6 7 8 9 |
<span style="color: #008000;"><strong><code> RED RED INVALID COLOR CODE Exception in thread "main" java.lang.NullPointerException at com.journaldev.util.SwitchStringExample.printColorUsingSwitch(SwitchStringExample.java:24) at com.journaldev.util.SwitchStringExample.main(SwitchStringExample.java:10) </code></strong></span> |
Keys points to know for java switch case String are:
- Java switch case String make code more readable by removing the multiple if-else-if chained conditions.
- Java switch case String is case sensitive, the output of example confirms it.
- Java Switch case uses String.equals() method to compare the passed value with case values, so make sure to add a NULL check to avoid NullPointerException.
- According to Java 7 documentation for Strings in Switch, java compiler generates more efficient byte code for String in Switch statement than chained if-else-if statements.
- Make sure to use java switch case String only when you know that it will be used with Java 7 else it will throw Exception.
Thats all for Java switch case String example.
Tip: We can use java ternary operator rather than switch to write smaller code.