Conditionals & Loops in JAVA

Conditionals & Loops in JAVA

Table of contents

Let's suppose we want to display something on the terminal, but only when a certain condition is met. For example, you want to display the message "User entered an even number" on the terminal, but only if the user has actually entered an even number as input.

In cases where we need to perform a task only if a certain condition is true, we use conditional statements in Java.

Types of conditional statement

There are four types of conditional statements in Java: if, if-else, else-if ladder, and switch statements. Let’s understand each of them one by one. However, we will discuss the switch statement in the next blog.

if Statement

The if statement is used when you are certain about the condition. This means that if a certain condition is met, only then should a task be executed. In such cases, we use the if statement.

Syntax
// Syntax of  if statement
if (condition) {
    Execute a task if above condition met
}
// other lines of codes
Ex :- Let’s say if user entered 2 as an input then you want to display “Congrats you entered 2.”
import java.util.Scanner;
public class Main {
     public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int num = in.nextInt();

        if (num == 2){
            System.out.println("Congrats you entered 2.");
        }
    }
}

Now the output message will only be displayed on screen when user entered 2 on the input else nothing will be displayed and program will exit.

I know this program doesn’t make any sense but to demonstrate how if condition works this is what i got 😂😂

if-else Statement

The if-else statement is used when we want to execute a piece of code if a certain condition is met, and a different piece of code if the condition is not met.

Syntax
// syntax of if-else statement
if (condition) {
    Execute a task if above condition met
} else {
    Execute a task if condition doesn't met
}
Ex :- Let's say in the example above, we want to display a message if the user does not enter 2. The message should say, "Sorry, you did not enter 2 as input" and then the program should end.
import java.util.Scanner;
public class Main {
     public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int num = in.nextInt();

        if (num == 2){
            System.out.println("Congrats you entered 2.");
        } else {
            System.out.println("Sorry you did not entered 2 as input");
        }
    }
}
by above example code when a user entered anything else except 2 a message will be displayed on the screen that “Sorry you did not entered 2 as input“

else-if ladder

The else-if ladder is used when we have multiple conditions to check, and based on which condition is met, we execute the corresponding code.

Ex :- Let's say we have a case where the user needs to enter any number from 1 to 5. If the entered number matches any of these, we display a message such as "You entered a number between 1 and 5, which is [number]."
import java.util.Scanner;
public class Main {
     public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int num = in.nextInt();

        if (num == 1){
            System.out.println("You entered 1.");
        }else if (num == 2){
            System.out.println("You entered 2.");
        }else if (num == 3){
            System.out.println("You entered 3.");
        }else if (num == 4){
            System.out.println("You entered 4.");
        }else if (num == 5){
            System.out.println("You entered 5.");
        } else {
            System.out.println("Sorry you did not entered any number between 1 to 5 as input");
        }
    }
}

In this scenario, the Java code will check if the number is 1, 2, 3, 4, or 5. If the number lies between 1 and 5, it will display the result accordingly. Otherwise, it will display, "Sorry, you did not enter a number between 1 and 5 as input."

So, basically, when we have a single condition to check, we use an if or if-else statement. However, if we need to check multiple conditions, we use an else-if ladder.

Loops in JAVA

When we need to repeat a statement or a block of code multiple times, or perform the same task again and again for a certain period of time, or until a condition is met, we use loops in Java.

There are three types of loops in Java:

  1. for loop

  2. while loop

  3. do-while loop

let’s understand them one by one.

for loop

The for loop in Java is used when you know in advance how many times you want to repeat a block of code. It allows you to loop through a block of code a specific number of times.

Think of it as a way to automate a repetitive task. For example, if you wanted to print a message 5 times, instead of writing the print statement 5 times, you can use a for loop to repeat the task.

Syntax
for (initialization; condition; update) {
    // code to be executed
}
  • initialization: This is where you set the starting point (e.g., starting from 0 or 1).

  • condition: This is the condition that keeps the loop running. The loop will continue to run as long as the condition is true.

  • update: This is where you change the value (e.g., increasing the counter) after each loop.

Ex :-
for (int i = 1; i <= 5; i++) {
    System.out.println("Hello, this is loop number: " + i);
}
  • int i = 1: Starts the loop with i equal to 1.

  • i <= 5: The loop runs as long as i is less than or equal to 5.

  • i++: After each loop, the value of i increases by 1.

  • This loop will print "Hello, this is loop number: 1" up to "Hello, this is loop number: 5."

Now there is verity in for loops called nested for loop

Nested for loop

A nested for loop means having one for loop inside another for loop. This is useful when you have to deal with more complex situations, like printing a pattern or going through a table of data (like rows and columns).

Syntax :-
for (initialization; condition; update) {
    // Outer loop code
    for (initialization; condition; update) {
        // Inner loop code
    }
}
Example :-
for (int i = 1; i <= 3; i++) {  // Outer loop
    for (int j = 1; j <= 3; j++) {  // Inner loop
        System.out.println("i = " + i + ", j = " + j);
    }
}
  • The outer loop runs 3 times (when i is 1, 2, and 3).

  • The inner loop runs 3 times for each iteration of the outer loop (when j is 1, 2, and 3).

  • The output will show all the combinations of i and j, like:

      i = 1, j = 1
      i = 1, j = 2
      i = 1, j = 3
      i = 2, j = 1
      i = 2, j = 2
      i = 2, j = 3
      i = 3, j = 1
      i = 3, j = 2
      i = 3, j = 3
    

Nested loops are commonly used for working with multidimensional data structures like matrices or grids.

While loop

The while loop in Java is used when you want to repeat a block of code but are unsure how many times it will be repeated in advance. The loop continues running as long as a specified condition remains true. Once the condition becomes false, the loop stops.

Think of it like this: As long as a certain condition is met (e.g., as long as you have money in your wallet), the task will keep repeating (e.g., buying items). The loop ends when the condition is no longer true (e.g., when you run out of money).

Syntax :-
while (condition) {
    // code to be executed
}
  • condition: The loop runs as long as this condition is true.

  • If the condition is false from the beginning, the code inside the loop won’t run at all.

Example :-
int i = 1;
while (i <= 5) {
    System.out.println("Hello, this is loop number: " + i);
    i++;
}
  • int i = 1: Initializes the loop variable i.

  • i <= 5: The loop will continue as long as i is less than or equal to 5.

  • i++: Increases the value of i by 1 after each iteration.

  • This will print "Hello, this is loop number: 1" up to "Hello, this is loop number: 5."

Do while loop

The do-while loop is similar to the while loop, but the difference is that it will always run at least once, even if the condition is false to begin with. This is because the condition is checked after the code is executed.

Syntax :-
do {
    // code to be executed
} while (condition);
  • condition: The loop continues if the condition is true, but the code inside the loop will always execute at least once.
Example :-
int i = 1;
do {
    System.out.println("This is loop number: " + i);
    i++;
} while (i <= 5);
  • int i = 1: Initializes the variable i.

  • The code inside the do block runs first, printing the message.

  • After each loop, the condition i <= 5 is checked. If true, the loop runs again; if false, the loop stops.

  • This loop also prints "This is loop number: 1" up to "This is loop number: 5."

What is the difference between while and do-while loop

  • In a while loop, the condition is checked before the loop runs. If the condition is false initially, the loop may not run at all.

  • In a do-while loop, the condition is checked after the code runs, so the code will always run at least once.


That's it for this blog. In the next blog, we will look at switch statements and their types, such as nested cases.

Until then, keep learning, keep sharing, and keep supporting.