14. switch with Strings


Answer:

This could be done with multiple case: labels, but the result is awkward.

    switch ( value ) { case 1: case 2: case3: do-something; break; case 4: case 5: case6: case 7: do-something; break; case 8: case 9: case 10: do-something; break; }

switch with Strings

Recall the syntax of the switch statement:

switch ( expression )
{
  case label1:
    statementList1 
    break;

  case label2:
    statementList2 
    break;

  case label3:
    statementList3 
    break;

  . . . other cases like the above

  default:
     defaultStatementList 
}

Starting with Java 7.0 the expression can be a String reference and the case labels can be String literals.

Matching of the expression with the case labels is done as if by String.equals().


Question 14:

Is "BTW".equals( " BTW ") true or false?