The switch Statement - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript The switch Statement - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, March 18, 2019

The switch Statement

The switch Statement


üThe switch statement provides another means to decide which statement to execute next
üThe switch statement evaluates an expression, then attempts to match the result to one of several possible cases
üThe expression of a switch statement must result in an integral type, meaning an int or a char
üEach case contains a value and a list of statements
üThe flow of control transfers to statement associated with the first value that matches.
The switch Statement

üThe general syntax of a switch statement is:


switch
and
case
are
reserved
words


switch (expression) {
    case value1:
        statement-list1
    case value2:
        statement-list2
    case value3:
        statement-list3
}

If expression
matches value2,
control jumps
from here

The switch Statement

üOften a break statement is used as the last statement in each case's statement list
üA break statement causes control to transfer to the end of the switch statement
üIf a break statement is not used, the flow of control will continue into the next case
üSometimes this can be appropriate, but usually we want to execute only the statements associated with one case.

The switch Statement

üA switch statement can have an optional default case
üThe default case has no associated value and simply 
uses the reserved word default
üIf the default case is present, control will transfer to it if
 no other case value matches
üIf there is no default case, and no other value matches, 
control falls through to the statement after the switch.
Switch example


char letter = 'b';
switch (letter) {
    case 'a':
        System.out.println("A");
        break;
    case 'b':
        System.out.println("B");
        break;
    case 'c':
        System.out.println("C");
        break;
    case 'd':
        System.out.println("D");
        break;
    default:
        System.out.println(”?");
}


No comments:

Post a Comment

Post Top Ad