Google News
logo
Java Program to Implement Switch Statement on Strings
Prior to Java 7, the switch statement could only be used on integral types (int, byte, short, char, and long) and their corresponding wrapper classes. However, starting from Java 7, the switch statement can also be used with strings.

Here's an example program that demonstrates how to use the switch statement on strings :
Program :
public class StringSwitch {
    public static void main(String[] args) {
        String dayOfWeek = "Sunday";
        
        switch (dayOfWeek) {
            case "Monday":
                System.out.println("Today is Monday");
                break;
            case "Tuesday":
                System.out.println("Today is Tuesday");
                break;
            case "Wednesday":
                System.out.println("Today is Wednesday");
                break;
            case "Thursday":
                System.out.println("Today is Thursday");
                break;
            case "Friday":
                System.out.println("Today is Friday");
                break;
            case "Saturday":
                System.out.println("Today is Saturday");
                break;
            case "Sunday":
                System.out.println("Today is Sunday");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}
Output :
Today is Sunday
We define a string dayOfWeek with the value "Sunday". We then use the switch statement to check the value of dayOfWeek. Each case label corresponds to a possible value of dayOfWeek. If dayOfWeek matches a case label, the corresponding code block is executed. If it doesn't match any of the case labels, the code block under default is executed.

Note that when using the switch statement with strings, the case labels must be string literals or final variables of type String. You cannot use variables or expressions as case labels.


Example 2 :
Program :
// Java Program to implement String on switch statements in Java

class Main {
  public static void main(String[] args) {

    // create a string
    String language = "Java";

    switch(language) {

      case "Java":
        System.out.println(language + " is a programming language.");
        break;

      case "JavaScript":
        System.out.println(language + " is famous for frontend and backend.");
        break;

      case "Python":
        System.out.println(language + " is famous for ML and AI.");
        break;

      default:
        System.out.println(language + " not found on record.");
        break;
    }
  }
}
Output :
Java is a programming language.