Home Java Java In Loops (for, while, do-while) – Improve Your Coding Speed

Java In Loops (for, while, do-while) – Improve Your Coding Speed

37
0
Loops in Java
Loops in Java

Java in Loops is a fundamental programming idea. We need to look at some real-life loop examples to understand what they are. Consider your everyday routine: you get up, brush your teeth, put on clothes, go to work, come home, eat, and then sleep. The next day, you repeat the process in the same order and go to sleep. This loop continues to repeat itself. A loop is a term that describes a series of actions that are repeated over and over again. We will learn about loops in Java in this java tutorial.

Need of Loops in Java

Consider software that must output a specific value of a variable 800 times. We are all aware that output is written using a systematic code system.out.println(“Text”); but, if we want to print this 800 times, we’ll have to repeat the code. That would take a lot of time and work, especially if you merely copied and pasted the same line 800 times. Let’s pretend you’ve successfully copied and pasted everything. If you have software that asks you to print the first 800 natural numbers, do so. Because you’d have to go to each of these lines and fit a number, the copy-paste method wouldn’t work. Loops come into play in this situation.

Loops make it simple to group all of the code that has to be processed repeatedly and place it under the scope. Then, the loop takes care of the rest.

Types of Loops

In Java, looping is defined as sequentially running some lines of code until a condition is met. We don’t want the loop to run indefinitely. Thus the state is crucial. The loop ends as soon as this condition is false.

There are three primary forms of loops in java:

  1. for loop
  2. Enhanced for loop
  3. while loop
  4. do-while loop

1. For loop

The three significant factors that determine the loop in Java are as follows. The initialization statement, a testing condition, and an increment or decrement component for incrementing/decrementing the control variable are all included in this section.

The basic syntax for a loop in Java is as follows:

for(initializing statement; testing condition; increment/decrement) { 
    //code to be iterated 
}

The beginning of the loop structure is marked by the initializing statement. It holds a variable with a programmatically defined starting value. When the control changes into the loop, this is the value of the control variable. This statement, however, is only used once.

If a variable is declared within this section, the scope of that variable is confined within the loop.

The following is an example Java programme that demonstrates how a for loop works:

package com.aspneto.loops;
import java.io.*;

public class ForLoop {
    public static void main(String[] args) {
        int i;

        for (i = 0; i <= 5; i++) {
            System.out.println("Test for loop at AspnetO");
            System.out.println("Value of i is = " + i);
        }
    }
}

Output:

Test for loop at AspnetO
Value of i is = 0
Test for loop at AspnetO
Value of i is = 1
Test for loop at AspnetO
Value of i is = 2
Test for loop at AspnetO
Value of i is = 3
Test for loop at AspnetO
Value of i is = 4
Test for loop at AspnetO
Value of i is = 5

Observe the value of the loop’s control variable I as it rises from 0 to 5 before stopping because the value of I reaches 6 and the condition is false. As a result, it is no longer in the loop.

2. Java loop enhancements

This is similar to a for loop but with several additional characteristics. It can be used to iterate over a collection’s elements without knowing the index of each one. You also don’t need to know how big the group is.

This modified for loop, however, has significant restrictions.

The values retrieved throughout the execution of the loop are read exclusively because this loop object is immutable. Therefore, you can’t change the collection’s values while using this loop, which is possible with other loops.

The Java extended for loop syntax is as follows:

for(<datatype> <variable_name>:<collection_name>){
    //Your statements
}

The following is a Java application that demonstrates the use of an improved for-loop:

package com.aspneto.loops;
import java.io.*;
    public class EnhancedFor {

        public static void main(String[] args) {
            String array[] = { "AspnetO", "Java", ".NET" };

            for (String a: array) {
                System.out.println(a);
            }
        }
}

Output

AspnetO
Java
.NET

3. While loop

While loops are necessary since we can’t always know how long a loop will last when we define it. For example, because we don’t see the size of the collection, for loops would be impractical to employ if we were given a dynamic pool and required to iterate through each entry. Then we’d have to utilize a while loop or an improved for a loop.

A while loop repeats a collection of statements until the boolean condition is false. The loop iterates as long as the supplied condition evaluates to true.

The condition of the loop structure is verified first, and only if the condition evaluates to true is the control passed into the loop structure. As a result, it’s known as an entry-controlled loop. The loop’s body usually includes a variable that controls the boolean condition specified earlier.

The basic syntax of Java while loop is:

while(boolean condition) {
    //Your statements
}

The loop ends as soon as the condition becomes false.

A Java application to demonstrate the use of a while loop is as follows:

package com.aspneto.loops;
import java.io.*;

public class WhileLoop {
    public static void main(String[] args) {
        int i = 0;

        while (i < 3) {
            System.out.println("Learn Java at AspnetO");
            System.out.println("Value of i is = " + i);
            i++;
        }
        
        System.out.println("Value of i now became " + i + " so break out of the loop..");
    }
}

Output:

Learn Java at AspnetO
Value of i is = 0
Learn Java at AspnetO
Value of i is = 1
Learn Java at AspnetO
Value of i is = 2

Value of i now became 5 so break out of the loop..

4. Use do-while loop in Java

The statement is executed first, and then the condition is checked in the Java do-while loop.

Aside from that, it’s very similar to the while loop. The distinction is that if the condition is true at the start of the loop, the statements will still be performed; however, they will not in the case of a while loop.

Because it checks the condition after the statements inside it are executed, this is an exit controlled loop.

An example Java programme demonstrating the use of the do-while loop is as follows:

package com.aspneto.loops;
import java.io.*;

public class DoWhileLoop {

    public static void main(String[] args) {
        int i = 0;
        
        do {
            i++;
            System.out.println("Learn Java at AspnetO");
            System.out.println("Value of i is = " + i);
        } while ( i != 3 );
    }
}

Output:

Learn Java at AspnetO
Value of i is 1
Learn Java at AspnetO
Value of i is 2
Learn Java at AspnetO
Value of i is 3

Summary

Looping is a fundamental idea in programming, and iterative tasks would be challenging to complete without them. A powerful loop notion in loops in Java would allow programmers to create programmes that could manage repetitive activities quickly.

Previous articleJava vs .Net – Key Differences to Decide Which is Better?

LEAVE A REPLY

Please enter your comment!
Please enter your name here

two × 1 =