Java program to implement switch statement on strings

Starting from Java 7, switch statements on Strings are supported in Java. Here's an example of how to implement a switch statement on a String in Java:

ref‮i:ot re‬giftidea.com
String fruit = "apple";

switch(fruit) {
    case "apple":
        System.out.println("The fruit is an apple.");
        break;
    case "banana":
        System.out.println("The fruit is a banana.");
        break;
    case "orange":
        System.out.println("The fruit is an orange.");
        break;
    default:
        System.out.println("The fruit is unknown.");
        break;
}

In the above example, we define a String variable fruit with a value of "apple". We then use a switch statement to check the value of fruit. The case statements check if fruit is equal to "apple", "banana", or "orange". If fruit matches any of these values, the corresponding message is printed. If fruit does not match any of these values, the default case is executed.

Note that the String values used in case statements must be constants (literal values), as opposed to variables or expressions. This is because the switch statement uses the equals method to compare the String values, and constant values are known at compile time.