You get a bonus - 1 coin for daily activity. Now you have 1 coin

Java branch and variant operator

Lecture



Option operator

The switch option operator organizes branching in several directions. Each branch is marked by a constant or a constant expression of some integer type (except long) and is selected if the value of a particular expression matches this constant. The whole structure looks like this.

switch (whole) {

case design1: operator1

case design2: operator2

. . . . .

case designN: operatorN

default: operator

}

The expression in parentheses can be of type byte, short, int, char, but not long. Integers or integer expressions made up of constants, constPyr should also not be of type long.

The variant operator is executed like this. All constant expressions are evaluated in advance, at compile time, and must have different values. First, the integer expression is calculated; If a. QHO coincides with one of the constants, then the operator marked by this constant is executed. Then all the following operators are executed ("fall through labels"), including the operator Oe £, and the work of the operator is terminated.

If none of the constants is equal to the value of the expression, then the operator Oe £ and all subsequent operators follow. Therefore, the default branch should be written last. The default branch may be absent, then in this situation the variant operator does nothing at all.

Thus, constants in case variants play the role of only labels, entry points to the variant operator, and then all remaining operators are executed in the order in which they are written.

Connoisseurs of Pascal

After performing one option, the switch statement continues to execute all remaining options.

Most often, you need to "go through" only one branch of operators. In this case, the break statement is used, immediately terminating the execution of the switch statement. You may need to execute the same statement in different branches of a case. In this case, we put several case tags in a row. Here is a simple example.

switch (dayOfWeek) {

case 1: case 2: case 3: case 4: case 5:

System.out.println ("Week-day") ;, break;

case 6: case 7:

System.out.println ("Week-end"); break;

default:

System.out.printlnt "Unknown day");

}

Comment

He forget to complete the options with the break statement.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming