Control Flow Flashcards
What goes inside an if statement’s parentheses?
A boolean expression
What goes inside an else statement’s parentheses?
Nothing, there are no parentheses.
Where is an else valid?
Only after an if statement.
How deep can ifs and elses be nested?
As deep as you make them, but nesting deep makes the code more difficult to read.
Does a switch require a default case?
No, it’s optional. The default keyword marks a catch-all case. If no other case matches, the default case executes.
Can we “fall through” (execute all cases after a match) a switch?
Switch cases “fall through” if there’s no break keyword. Once a case matches, it runs the rest of the code in the switch until it hits a break.
Can we switch on a String value?
Yes
Can we switch on a LocalDate?
Identify the three parts of a for loop inside its parentheses. Are all parts required?
1) The first initializes variables or state.
2) The second is a boolean expression. If it evaluates to true, the for’s code block executes, just like a while statement.
3) The third clause runs after each loop. It can be used to update variables or state.
Is this valid?:
for (int x = 5, y = 10; x < y && x > -y; x+=2, y++) { }
Does it terminate?
It does not cause an exception but it does terminate.
What can a while loop compute that a for loop can’t?
A for loop cannot recreate.
The do/while loop seems unnecessary. Is it?
A do/while must be used when you want the loop to be evaluated once, and if the condition is met, then evaluate it again.
The main difference with a while loop is that it is evaluated at least once. Of course you can evaluate the loop and then begin witha a while loop.
What is an enhanced for loop? What can it operate on?
It is mainly used to traverse a collection of elements including array
if statements are useful when:
We are evaluating an expression, like x < 5, instead of checking a specific value.
Conditions are complex.
A range of values triggers a single code block.
switch statements are useful when:
We have a relatively small, fixed set of values to evaluate.
Each value’s branching is unique