Using "||" in switch statements in java

The part of the Java program that I am doing is asking the user for his home country. The other part uses the switch statement, and I get an error. Error: The operator || is undefined for the argument type(s) java.lang.String, java.lang.String. Here is the method where the problem occurs:

public static String getCountryMessage(String countryName) {
    switch (countryName) {
    case "USA":
        return "Hello, ";
    case "England" || "UK":
        return "Hallo, ";
    case "Spain":
        return "Hola, ";
    case "France":
        return "Bonjour, ";
    case "Germany":
        return "Guten tag, ";
    default:
        return "Hello, ";
    }
}

How to use && and || in a java switch statement?

+5
source share
2 answers

I do not think that you can use such conditional expressions in switch statements. It would be simpler and easier to write this instead:

case "England":
case "UK":
    return "Hallo";

This is a bad case - if your string matches England or Great Britain, it will return Hallo.

+14
source

Use the missed case:

case "England":
case "UK":
    return "Hallo, ";
+7
source

All Articles