Flissie
Flissie

Reputation: 63

using method in switch case statements

I was wondering if you could use methods such as 'contains()' in the case of a switch case. I am trying to make the following if statements into a switch case:

String sentence;
if(sentence.contains("abcd")){
// do command a
}
else if(sentence.contains("efgh")){
// do command b
}
else if(sentence.contains("ijkl")){
// do command c
}
else{
//do command d
}

Thank you very much for your help.

Upvotes: 6

Views: 13187

Answers (4)

Andy Thomas
Andy Thomas

Reputation: 86381

No, because the case constant must be either:

  • A constant expression
  • Or the name of an enumerator of the same type as the switch expression.

A method call is neither of these.

From the Java Language Specification, section 14.11: The switch statement:

Every case label has a case constant, which is either a constant expression or the name of an enum constant.

Upvotes: 1

Dyndrilliac
Dyndrilliac

Reputation: 791

Yes, you can get an equivalent bit of code to work using the switch statement assuming you are using JDK 7 or higher. JDK 7 introduced the ability to allow String objects as the expression in a switch statement. This generally produces more efficient bytecode compared to a chain of if-then-else statements invoking the equals method.

String pattern;
String sentence;

if (sentence.contains(pattern))
{
    switch (pattern)
    {
        case "abcd":

            // do command a
            break;

        case "efgh":

            // do command b
            break;

        case "ijkl":

            // do command c
            break;

        default:

            // do command d
            break;
    }
}

Do note however that this only works because the contains method expects a String object, and String objects are now valid inside switch statements. You can't generalize this to work with objects of an arbitrary type.

Upvotes: 0

Iłya Bursov
Iłya Bursov

Reputation: 24146

actually you can change this if into switch, but its kinda unreadable:

    final String sentence;
    int mask = sentence.contains("abcd") ? 1 : 0;
    mask |= sentence.contains("efgh") ? 2 : 0;
    mask |= sentence.contains("ijkl") ? 4 : 0;
    switch (mask) {
    case 1:
    case 1 | 2:
    case 1 | 4:
    case 1 | 2 | 4:
        // do command a
        break;
    case 2:
    case 2 | 4:
        // do command b
        break;
    case 4:
        // do command c
        break;
    default:
        // do command d
    }
}

Upvotes: 3

William B.
William B.

Reputation: 83

no you cant. case statements can only compare the values of the thing being "switch"ed. Infact, java only 'recently' started supporting switch statements on Strings, since they are objects and not primitive. In general, switch statements will work only on primitives. The only exception to that, as far as im aware, is for Strings

Upvotes: -1

Related Questions