Topic 3.3 and 3.4: Using Operators and Decision Constructs - Create if and if/else and ternary constructs and use a switch statement Flashcards
What is a
switch statement?
This provides a way to execute different blocks of code based on the value of a variable or an expression.
What is the
ternary operator?
This operator is a concise way to write if/else statements in a single line.
What is the syntax of a switch statement?
Syntax:
switch (variable) { case value1: // Code to be executed if variable equals value1 break; case value2: // Code to be executed if variable equals value2 break; // Additional case statements default: // Code to be executed if variable doesn't match any case break; }
What is the syntax of the
ternary operator?
Syntax is:
variable = (condition) ? expression1 : expression2;
What is the purpose of the break statement in a switch statement?
The break statement is used to prevent fall-through behavior, where execution continues to the next case even if a match is found.
What types of data can be used with a switch statement?
A switch statement works with the:
- byte, short, char, and int primitive data types.
- It also works with enumerated types, the String class,
- and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
How does a switch statement work?
The switch statement evaluates the value of the variable and matches it with the values specified in the case statements.
If a match is found, the corresponding code block is executed until a break statement is encountered, which exits the switch statement.
If no match is found, the code block associated with the default statement is executed (if provided).
How does the ternary operator work?
The condition is evaluated first. If it is true, expression1 is assigned to the variable; otherwise, expression2 is assigned.
variable = (condition) ? expression1 : expression2;