Which is not a looping statement in Java

Loops are a fundamental concept in programming. In order to understand what loops are, we have to look at some real life cases of loops. Consider your daily routine, you wake up, you brush, you wear clothes and then head off to work, come back, eat and then sleep off. Again the next day, you do the same things in the same order and go to sleep again. This cycle keeps on repeating. This concept of repetitive actions performed time and again is called a loop. In this java tutorial, we will learn about the loops in java.

Need of Loops in Java

Imagine a program which is required to output a particular value of a variable 800 times. Now we all know that the code for writing output is System.out.println[“Text”]; But in order to print this 800 times we will need to write the same line 800 times in the code. That would take up a lot of effort which is particularly just copy pasting the same sentence 800 times. Let us say that you have managed to copy paste the entire thing easily. Now if there is a different program which requires you to print the first 800 natural numbers. The copy paste method would not work because you still would have to go to all these lines and fit a number. That’s where loops come in to play. Loops make it very easy to group all the code that’s needed to be repetitively processed and throw it under scope. The loop does the remaining job.

Loops in Java

Looping in Java is defined as performing some lines of code in an ordered fashion until a condition is false. The condition is important because we do not want the loop to be running forever. As soon as this condition is false, the loop stops.
In Java there are three primary types of loops:-

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

1. For loop in Java

Java for loop consists of 3 primary factors which define the loop itself. These are the initialization statement, a testing condition, an increment or decrement part for incrementing/decrementing the control variable.

The basic syntax of java for loop goes like this:

for[initializing statement;testing condition;increment/decrement]
{
//code to be iterated
}

The initializing statement marks the beginning of the loop structure. It contains a variable with some initial value that is defined by the programmer. This is the value of the control variable when the control shifts into the loop. However this statement is executed only once.
If a particular variable is declared within this part, then the scope of the variable remains limited within the loop.

The control flow can be explained with a flowchart diagram:

An example Java program explaining the functioning of a for loop:

package com.dataflair.loops;
import java.io. * ;
public class ForLoop {
  public static void main[String[] args] {
    int i;
    for [i = 0; i  ar = new ArrayList < >[];
    try {
      for [i = 0; i 

Chủ Đề