Introduced in Java 7, you can use switch statement with Strings. This makes code more readable as sometimes the string value of switch case variable makes more sense. Let’s see how can we achieve this:
Java Switch with Strings Examples
Example 1: Checking day of the week using switch case
public class SwitchStringExample {
public static void main(String[] args) {
String dayOfWeek = "Tuesday";
switch (dayOfWeek) {
case "Monday":
System.out.println("First day of the week");
break;
case "Tuesday":
System.out.println("Second day of the week");
break;
case "Wednesday":
System.out.println("Third day of the week");
break;
case "Thursday":
System.out.println("Two days to go for weekend");
break;
case "Friday":
System.out.println("A day before weekend");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend");
break;
default:
System.out.println("The data is invalid");
break;
}
}
}
Explanation:
- Variable: The value of the variable
dayOfWeek
determines which case is to be executed. - Switch Statement: The
switch
statement evaluates the value ofdayOfWeek
, the value can be an expression. - Case Labels: Case label is a string literal in this example. When the value of
dayOfWeek
matches a case label, the corresponding block of code is executed. - Break Statement: After the execution of case block, the break statement terminates the further execution.
- Default Case: The
default
case is executed if none of the other cases match.
Points to Note:
- Case Sensitivity: The comparison of variable and case literal is case-sensitive, which means “Tuesday” and “tuesday” would not be considered a match.
- Efficiency: The
switch
statement with strings internally useshashCode()
andequals()
methods of theString
class, making it relatively efficient. - Null Values: If the value of String variable is
null
, aNullPointerException
will be thrown. It is always advisable to ensure that the string is notnull
before using it in aswitch
statement.
Example 2: Determining Type of Beverage
public class BeverageTypeExample {
public static void main(String[] args) {
String beverage = "Tea";
switch (beverage) {
case "Coffee":
case "Tea":
System.out.println("Hot Beverage");
break;
case "Juice":
case "Soda":
System.out.println("Cold Beverage");
break;
case "Water":
System.out.println("Normal Beverage");
break;
default:
System.out.println("Unknown Beverage Type");
break;
}
}
}
Leave a Reply