Developer community
0 votes
967 views
asked by Sr Member (4.8k points) 10 25 31 | 967 views

1 Answer

0 votes
An alternative to a series of else if is the switch statement.
The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.
The expression used in the switch statement must return an int or an enumerated value.
The syntax of the switch statement is as follows.

switch (expression) {
case value_1 :

     statement (s);
     break;
case value_2 :
     statement (s);
     break;
  .
  .
  .
case value_n :
     statement (s);
     break;
default:
     statement (s);
}
Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.

Here is an example of the switch statement:

public class MainClass {

  public static void main(String[] args) {
    int i = 1;
    switch (i) {
    case 1 :
        System.out.println("One.");
        break;
    case 2 :
        System.out.println("Two.");
        break;
    case 3 :
        System.out.println("Three.");
        break;
    default:
        System.out.println("You did not enter a valid value.");
    }
  }

}
answered by Expert (11.4k points) 14 23 30

Related questions

0 votes
2 answers
asked by rock Expert (15k points) 15 23 31 | 953 views
0 votes
2 answers
0 votes
1 answer
asked by rock Expert (15k points) 15 23 31 | 27 views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 25 31 | 7 views
0 votes
1 answer
asked by augustaina Sr Member (4.8k points) 10 25 31 | 18 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users