In Java, you can use control flow statements to alter the sequential execution of your code based on certain conditions. The main control flow statements in Java are if-else statements, switch statements, and loops (such as for, while, and do-while). Let’s take a look at each of these statements and their usage:
- if-else statements: The if-else statement allows you to execute a block of code based on a condition. It has the following syntax:
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
Example:
int x = 5; if (x > 0) { System.out.println("x is positive"); } else { System.out.println("x is non-positive"); }
- switch statements: The switch statement is used to select one of many code blocks to be executed based on the value of a variable. It has the following syntax:
switch (variable) { case value1: // code to execute if variable equals value1 break; case value2: // code to execute if variable equals value2 break; // more cases... default: // code to execute if none of the cases match }
Example
int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; // more cases... default: dayName = "Invalid day"; } System.out.println("The day is: " + dayName);
- loops: Loops are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops in Java: for, while, and do-while.
- for loop: The for loop allows you to execute a block of code a specific number of times. It has the following syntax:
for (initialization; condition; update) { // code to be executed }
Example:
for (int i = 1; i <= 5; i++) { System.out.println(i); }
- while loop: The while loop executes a block of code as long as a condition is true. It has the following syntax:
while (condition) { // code to be executed }
Example:
int i = 1; while (i <= 5) { System.out.println(i); i++; }
- do-while loop: The do-while loop is similar to the while loop, but it ensures that the code block is executed at least once, even if the condition is initially false. It has the following syntax:
do { // code to be executed } while (condition);
Example:
int i = 1; do { System.out.println(i); i++; } while (i <= 5);
These are the basic control flow statements in Java. They provide you with the flexibility to make decisions and repeat code execution based on different conditions.