Java Part 4: Control Flow Statements In Java

JAVA PART 4: Control Flow Statements IN JAVA


Please Subscribe Youtube| Like Facebook | Follow Twitter

Control Flow Statements In Java

In this article, we will provide a detailed overview of control flow statements in Java and provide examples of how they are used in Java programming.

Control flow statements are an essential part of any programming language. They allow you to control the flow of execution in a program based on specific conditions. In Java, there are several control flow statements, including if-else, switch, for loop, while loop, and do-while loop. Each of these statements serves a different purpose, but they are all useful in controlling the flow of a Java program.

If-Else Statement

In Java, the if-else statement is a control flow statement that allows you to execute a block of code based on a condition. It works by evaluating an expression and, if the expression is true, executing a block of code. If the expression is false, the code inside the else block is executed. Here is the syntax for an if-else statement:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

In some cases, you may need to evaluate multiple conditions. In these cases, you can use the else if statement. The else if statement allows you to evaluate multiple conditions and execute different blocks of code based on the result of the evaluations. Here is the syntax for multiple if-else statement:

if (condition1) {
  // code to be executed if condition1 is true
} elseif (condition2) {
  // code to be executed if condition2 is true
} else {
  // code to be executed if all conditions are false
}

Here is an example of an if-else statement in Java:

public class Example {
   public static void main(String[] args) {
      int number = 5;
      if(number > 0) {
         System.out.println("The number is positive.");
      } else if(number < 0) {
         System.out.println("The number is negative.");
      } else {
         System.out.println("The number is zero.");
      }
   }
}

Output

The number is positive.

In this example, we’re checking if the number variable is positive, negative, or zero. If the number is greater than 0, it will print “The number is positive.” If the number is less than 0, it will print “The number is negative.” If the number is 0, it will print “The number is zero.”

Switch Statement

A switch statement is used to select one of several code blocks to be executed. The block of code that is executed depends on the value of an expression. Default case is executed when none of the cases matches the value of the switch expression. The default case is optional, and it is usually used as a fallback option when none of the other cases match. It is similar to the “else” statement in an if-else statement. Here is the syntax for a switch statement:

switch (expression) {
  case value1:
    // code to be executed if expression is equal to value1
    break;
  case value2:
    // code to be executed if expression is equal to value2
    break;
  default:
    // code to be executed if expression is not equal to any of the values
}

Here is an example of a switch statement in Java:

public class Main {
  public static void main(String[] args) {
    int day = 4;
    switch (day) {
      case 1:
        System.out.println("Monday");
        break;
      case 2:
        System.out.println("Tuesday");
        break;
      case 3:
        System.out.println("Wednesday");
        break;
      case 4:
        System.out.println("Thursday");
        break;
      case 5:
        System.out.println("Friday");
        break;
      default:
        System.out.println("Weekend");
    }
  }
}

Output

Thursday

In this program, the variable day is assigned a value of 4. The program then uses a switch statement to check the value of day and execute the corresponding block of code.

Since day is equal to 4, the program executes the block of code associated with the case 4 label, which is to print “Thursday”.

Therefore, the output of the program is “Thursday”.

For Loop

A for loop is used to execute a block of code a specific number of times. Here is the syntax for a for loop:

for (initialization; condition; increment) {
  // code to be executed
}

In a for loop, the initialization sets the starting point, the condition determines when to stop, and the increment increases the counter. The code inside the curly braces is executed each time the loop runs.

Here is an example of a for loop in Java:

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      System.out.println(i);
    }
  }
}

Output

0
1
2
3
4

In this program, a for loop is used to iterate from 0 to 4. The loop condition i < 5 is true for the values of i from 0 to 4.

Inside the loop, the program prints the value of i using the System.out.println(i) statement. The loop body executes five times, once for each value of i from 0 to 4.

Therefore, the output of the program is the sequence of numbers from 0 to 4, each on a new line.

Break and Continue Statements Inside a For Loop

break and continue are two control flow statements that allow you to alter the normal flow of the loop.

The continue statement is used inside a loop to skip the current iteration and continue with the next one. This means that any code below the continue statement in that iteration is not executed. The loop will then continue with the next iteration as if the current one never happened.

The break statement, on the other hand, is used to terminate a loop prematurely. When the break statement is encountered, the loop is exited immediately, and the program execution continues with the statement that follows the loop.

Both continue and break statements can be useful in situations where you want to skip certain iterations of a loop or stop the loop altogether based on some condition. For example, you might want to skip certain iterations of a loop if the data being processed is not relevant, or you might want to stop the loop when a certain condition is met, such as when you’ve found the data you were searching for.

Here is an example of using break and continue in a for loop in Java:

public class LoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 3) {
                continue;
            }
            if (i == 5) {
                break;
            }
            System.out.println(i);
        }
    }
}

Output

1
2
4

Loop iterates from 1 to 10, but when i is 3, the continue statement is encountered and that iteration is skipped. Then, when i is 5, the break statement is encountered and the loop is terminated, so only the values 1, 2, and 4 are printed to the output.

While Loop

A while loop is used to execute a block of code repeatedly while a particular condition is true. Here is the syntax for a while loop:

while (condition) {
  // code to be executed
}

In a while loop, the condition is evaluated at the beginning of each iteration. If the condition is true, the code inside the curly braces is executed. This continues until the condition becomes false.

Here is an example of a while loop in Java:

public class Main {
  public static void main(String[] args) {
    int i = 0;
    while (i < 5) {
      System.out.println(i);
      i++;
    }
  }
}

Output

0
1
2
3
4

In this program, a while loop is used to iterate from 0 to 4. The loop condition i < 5 is true for the values of i from 0 to 4.

Inside the loop, the program prints the value of i using the System.out.println(i) statement, and then increments i using the i++ statement. The loop body executes five times, once for each value of i from 0 to 4.

Therefore, the output of the program is the sequence of numbers from 0 to 4, each on a new line.

Do-While Loop

A do-while loop is similar to a while loop, but the block of code is executed at least once, even if the condition is false. Here is the syntax for a do-while loop:

do {
  // code to be executed
} while (condition);

In a do-while loop, the code inside the curly braces is executed first, and then the condition is evaluated. If the condition is true, the loop continues to run. If the condition is false, the loop ends.

Here is an example of a do-while loop in Java:

public class Main {
  public static void main(String[] args) {
    int i = 0;
    do {
      System.out.println(i);
      i++;
    } while (i < 5);
  }
}

Output

0
1
2
3
4

In this program, a do-while loop is used to iterate from 0 to 4. The loop body executes at least once, regardless of the loop condition.

Inside the loop, the program prints the value of i using the System.out.println(i) statement, and then increments i using the i++ statement. The loop body executes five times, once for each value of i from 0 to 4.

Therefore, the output of the program is the sequence of numbers from 0 to 4, each on a new line.

Conclusion

In conclusion, control flow statements are essential for programming as they help to determine the path a program takes based on certain conditions. If-else, switch, for loops, while loops, and do-while loops are the most common types of control flow statements used in Java. Each statement has its own syntax and usage that can be applied in various situations.

Java Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *