Java Conditions and Loops
Conditional statements and loop statements are core structures in programming used to control the flow of program execution. Conditional statements allow programs to execute different code paths based on specific conditions, while loop statements allow programs to repeatedly execute a block of code until a certain termination condition is met.
Conditional Statements
1. if Statement
The if statement is the most basic conditional control structure. If the conditional expression inside the parentheses evaluates to true, the subsequent code block is executed.
2. if-else Statement
The if-else statement executes one code block when the if condition is true, and another code block when the condition is false.
3. if-else if-else Statement
When multiple conditions need to be evaluated, this structure can be used. It checks each condition in order, and once a condition evaluates to true, it executes the corresponding code block and then exits the entire structure.
4. switch Statement
The switch statement is suitable for evaluating a variable against multiple possible values. Starting from Java 14, switch introduced more concise "arrow" syntax and expression form.
Traditional switch (requires break)
Modern switch Expression (JDK 14+)
This new syntax is more concise, doesn't require break, and can return a value as an expression.
Loop Statements
1. for Loop
The for loop is ideal when the number of iterations is known in advance. It consists of three parts: initialization, loop condition, and iteration statement.
2. Enhanced for Loop (For-Each Loop)
The enhanced for loop is used to iterate over all elements in an array or collection. The syntax is more concise and less error-prone.
3. while Loop
The while loop checks the condition before the loop body executes. As long as the condition is true, the loop continues. It's suitable for scenarios where the number of iterations is uncertain.
4. do-while Loop
The do-while loop is similar to the while loop, but it executes at least once because the condition check happens after the loop body executes.
Loop Control Statements
-
break: Immediately terminates and exits the entire current loop. -
continue: Skips the remaining part of the current iteration and proceeds directly to the next iteration.