Control Structures

6. Exception Handling (try-catch)

6.2. Explanation:

1. Uses a for-each loop to iterate over an array.

2. if-else-if classifies numbers as positive, negative, or zero.

3. continue skips negative numbers; break exits on zero.

4. switch categorizes positive numbers by magnitude.

5. try-catch handles a potential division-by-zero error.

 

4. Key Points

1. Nesting: Control structures can be nested (e.g., loops inside if statements).

2. Scope: Variables declared inside a block (e.g., {} in a loop or if) are local to that block.

3. Infinite Loops: Ensure loop conditions eventually become false to avoid infinite loops (e.g., while (true) without a break).

4. Java 12+ Enhancements: Switch expressions and pattern matching for instance of (Java 14+) simplify control flow.

5. Performance: Use break and continue judiciously to avoid confusing code. Prefer for-each for collections when index access isn’t needed.