Chapter 4 Flashcards
What are the shortcut operators for incrementing or decrementing a variable?
++ (increment) and – (decrement).
What is the difference between prefix and postfix notation in increment/decrement?
Prefix (++number): Increment/decrement happens before the rest of the expression is evaluated.
Postfix (number++): Increment/decrement happens after the rest of the expression is evaluated.
What is the syntax of a while loop in Java?
while (condition) {
statements;
}
When does a while loop stop executing?
When the condition becomes false.
What is a common mistake that causes infinite loops?
Failing to update the condition variable (e.g., forgetting to decrement x in while (x > 0)).
How can a while loop be used for input validation?
while (number < 1 || number > 100) {
System.out.println(“Invalid input!”);
number = keyboard.nextInt();
}
What is the syntax of a do-while loop?
do {
statements;
} while (condition);
How is a do-while loop different from a while loop?
A do-while loop always executes the body at least once before testing the condition.
What is the syntax of a for loop in Java?
for (initialization; test; update) {
statements;
}
What are the three sections of a for loop?
Initialization: Initializes the loop control variable(s).
Test: Condition that determines whether the loop runs.
Update: Updates the loop control variable(s).
Why should you avoid modifying the control variable inside the body of a for loop?
It makes the code harder to debug and maintain.
What happens if you omit all parts of a for loop (e.g., for(;;))?
It creates an infinite loop.
Can a for loop initialize and update multiple variables?
Yes, for example:
java
Copy code
for (int i = 0, j = 10; i < 5 && j > 5; i++, j–) {
// Loop body
}
What does the break statement do in a loop?
It terminates the loop immediately.
What does the continue statement do in a loop?
It skips the current iteration and moves to the next iteration.
Why should break and continue be avoided?
They make code harder to read and debug.
How does a nested loop execute?
The inner loop runs completely for each iteration of the outer loop