Java Switch String
Java programming has conditional statements like if-else to represent different conditions in a program. But when the number of conditions is more it is not suitable to use the if-else statement. In order to provide a solution for the problem, Java programming language supports switch-case statement with strings since JDK version 7. Previous versions of Java only supported enum and int types.
Switch case statement in Java
The Switch case statement provides a way to select and execute the specific condition from different defined conditions.
The switch statement allows a number of executable paths. A switch statement can work with different data types like byte, char, short, and int. It also allows enum and String objects.
An if-else statement checks the conditions based on a range of possible values, whereas the switch statement checks the condition based on a single value.
Syntax of Switch case:
Example of a switch statement in Java:
Java Program to demonstrate switch statement.
SwitchExample.java
Output:
Size of the shirt: Extra Large
The above code demonstrates the use of a switch statement in a Java program. The variable numb is used as the user input and according to the defined cases, the size of the shirt is displayed on the console.
Java Switch Case with String
Java programming uses String objects for implementing various conditional statements. To implement the conditions with Strings, a switch case with String is provided by Java in JDK version 7.
The Java switch case with String makes the code more readable by removing the multiple if-else statements.
The String objects used in the Java switch case are case-sensitive.
As a Java switch case with String uses the String.equals() method to compare the value passed by the user and the case value, a NULL check must be added in order to avoid NullPointerException.
Example 1:
Java Program to demonstrate switch case with string.
SwitchStringExample.java
Output:
Black color identified No color Red color identified
In the above Java code, the switch statement uses the name of the case as a String literal. The different string cases return a value to the calling method getColor().
Example 2:
Java Program to demonstrate multiple switch conditions.
SwitchStringExample2.java
Output:
Violet color identified Orange color identified No color identified
The above Java code implements the Switch statement with more than one case. It displays the output on the console if one of the cases is matched.
In this article we have discussed the Switch statement in Java, different data types supported by switch statement especially String.