Java Fundamentals – Part 04

Hello guys, I am back with my 4th article in my Java Fundamentals series. I hope you guys understood the concepts I explained so far. Today, I am going to talk about Iterations in Java language.

Why iterations?

There is something that we do over and over again as humans. We call them habits. We can make our computer programs do something over and over again.

For example, we can make a program search a file for particular information or make it generate random numbers over and over again. There are 3 ways in Java to perform repetition.

1. While Loops

        //Part 1 - Declaring and initializing a variable
        int number = 1;

        //Part 2 - Looping 
        while (number <= 10){
            System.out.println("Number " + number);
            
            //Part 3 - Changing the value (Incrementing or Decrementing)
            number++;
        }

As you can see, we have 3 main parts in a while loop. The flow of this code snippet is going to go like this.

  • Declaring a variable (number) that is going to be used in the while loop
  • Checking if the number is lesser than or equals to 10.
  • Executing the code inside the while loop and incrementing the value of the number
  • Checking the condition again

The repetition process will happen until the condition in the while loop evaluates false. When that happens, the program will exit from the while loop and move on.

2. For Loops

For loop are very similar to the while loop. All we have to do is move those parts we discussed earlier. The same code in for loop looks like this.

        //All 3 parts are inside the for loop condition
        for (int number = 1; number <= 10; number++){
            System.out.println("Number " + number);
        }

As you can see, both the variable declaration part and changing its value has been brought inside the condition. The flow of a for loop goes like this.

  • Declaring the variable
  • Checking the condition
  • Executing the loop body
  • Changing the value

You might be wondering why we have two loop types if it is the same code. Well, there are is a big difference. We use a for loop when we know the number of iterations. We use a while loop when we don’t know the number of iterations.

For example, we can use a for loop for something like this.

        Random random = new Random();
        int magicNumber = 6;

        //Checking if the random generated number matches the magic number
        while (magicNumber != random.nextInt(10)){
            System.out.println("Trying again");
        }
        System.out.println("Found the magic number");

We can’t say, “Ok. You will find the magic number in ## many iterations”. In moments like this, we have to use a while loop.

And by now, you may have also realized that we can use a while loop anywhere.

3. Do While Loops

This is same as the while loop. The only difference is that we are executing the loop body before checking the condition for the first time.

        //Part 1 - Declaring and initializing a variable
        int number = 1;

        //Part 2 - Looping
        do {
            System.out.println("Number " + number);
            
            //Part 3 - Changing the value (Incrementing or Decrementing)
            number++;
        } while (number <= 10);

The flow of this loop goes like this.

  • Declaring the variable
  • Executing the loop body
  • Changing the value
  • Checking the condition

Nested Loops

This is same as nested if statements. When we use a loop inside a loop, we call it a nested loop.

        int numOfLines = 5;

        //This loop decides the number of rows
        for (int i = 0; i < numOfLines; i++) {

            //This loop handles the number of columns
            for (int j = 0; j <= i; j++) {
                System.out.print("* ");
            }

            //Printing the space
            System.out.println();
        }

This code snippet will print a triangle on the screen.

Triangle from the code

This is it for today guys. Thank you for reading the article. If you liked it please drop a like and share it among your friends. If you are new, subscribe and follow our blog to get notifications when I publish new articles. Stay safe ✌

Published by Thisura Thenuka

I am a passionate software engineering student. But cricket is my first love ❤

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: