In this Java program, we will learn to use switch case statements with strings. In Java, you can use the switch statement to perform different actions based on the value of a string. Starting from Java 7, it's possible to use strings in switch statements.
Here is an example of how you can use a switch statement to perform different actions based on the value of a string.
Java Program For Switch Case Statement on String
public class SwitchStringExample {
public static void checkString(String str) {
switch (str) {
case "January":
System.out.println("The month is January.");
break;
case "February":
System.out.println("The month is February.");
break;
case "March":
System.out.println("The month is March.");
break;
default:
System.out.println("The month is not January, " +
"February, or March.");
break;
}
}
public static void main(String[] args) {
String month = "February";
checkString(month);
}
}
Output
The month is February.
In this example, the checkString method takes a string as a parameter, and then uses a switch statement to check its value. Based on the value of the string, the method prints a different message to the console. The main method first calls the checkString method and pass it the string "February". The output will be : "The month is February."
It's worth noting that for the switch statement to work with strings, the string should be a constant variable, i.e a variable whose value will not change after it's been initialized.
When the case statement is matched, the code is executed until it reaches a break statement. If no break statement is used, it will execute any case statements that follow the matched case statement.