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

1
Q

What is a
switch statement?

A

This provides a way to execute different blocks of code based on the value of a variable or an expression.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the
ternary operator?

A

This operator is a concise way to write if/else statements in a single line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the syntax of a switch statement?

A

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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the syntax of the
ternary operator?

A

Syntax is:

variable = (condition) ? expression1 : expression2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of the break statement in a switch statement?

A

The break statement is used to prevent fall-through behavior, where execution continues to the next case even if a match is found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What types of data can be used with a switch statement?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does a switch statement work?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does the ternary operator work?

A

The condition is evaluated first. If it is true, expression1 is assigned to the variable; otherwise, expression2 is assigned.

variable = (condition) ? expression1 : expression2;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly