Post

Created by @adamvaughn
 at November 6th 2023, 12:56:55 am.

Post 4: Control Flow Statements in Java

In Java programming, control flow statements are used to determine the execution order of statements within a program. These statements allow you to control the flow of your program based on certain conditions or loops. In this post, we will cover the basics of control flow statements and provide examples to help you understand their usage.

  1. if-else statement: The if-else statement is used to make decisions in your program. It allows you to execute a block of code if a certain condition is true, and another block of code if the condition is false.
if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

Example:

int age = 18;

if (age >= 18) {
  System.out.println("You are an adult.");
} else {
  System.out.println("You are a minor.");
}
  1. switch statement: The switch statement is used to perform different actions based on different values of a variable. It allows you to specify multiple cases and execute different blocks of code based on the value of the variable.
switch (variable) {
  case value1:
    // code to be executed if variable == value1
    break;
  case value2:
    // code to be executed if variable == value2
    break;
  ...
  default:
    // code to be executed if none of the cases match
    break;
}

Example:

int dayOfWeek = 5;

switch (dayOfWeek) {
  case 1:
    System.out.println("Sunday");
    break;
  case 2:
    System.out.println("Monday");
    break;
  case 3:
    System.out.println("Tuesday");
    break;
  // and so on...
  default:
    System.out.println("Invalid day");
    break;
}
  1. for loop: The for loop is used to execute a block of code a specific number of times. It consists of three parts: initialization, condition, and update. The block of code is executed as long as the condition is true.
for (initialization; condition; update) {
  // code to be executed
}

Example:

for (int i = 1; i <= 5; i++) {
  System.out.println(i);
}
  1. while loop: The while loop is used to repeatedly execute a block of code as long as a certain condition is true. The condition is checked before each iteration.
while (condition) {
  // code to be executed
}

Example:

int count = 1;

while (count <= 5) {
  System.out.println(count);
  count++;
}
  1. do-while loop: The do-while loop is similar to the while loop, but the condition is checked after each iteration. This guarantees that the code inside the loop is executed at least once.
do {
  // code to be executed
} while (condition);

Example:

int count = 1;

do {
  System.out.println(count);
  count++;
} while (count <= 5);

These control flow statements are integral to controlling the flow and logic of your Java programs. Practice using them in various scenarios to become comfortable with their syntax and behavior.