The Conditional Operator and the 'switch' Statement

Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.

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?