Looping statement in Java

The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the looping statements(for, while, do-while) supported by the Java programming language.

There are various advantages of using looping statements such as:

  1. Firstly, memory utilization is reduced
  2. It reduces length of code
  3. Time for execution is reduced
  4. Code redundancy can be avoided using it
  • The while and do-while Statements

The while loop is a control flow statement that continually executes a block of statements while a particular condition is true.

Syntax

While-Loop

Example

You can implement an infinite loop using the while statement as follows:

Do-While Loop
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:

  • The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

Syntax


For-Loop

When using this version of the for the statement, keep in mind that:

  • The initialization expression initializes the loop; it’s executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:

Example

Output

The following program, EnhancedForDemo, uses the enhanced for loop to iterate through the array(for each loop).  Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It works on elements basis not index. It returns element one by one in the defined variable.

Syntax

Example

In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:

Output

We recommend using this form of the for statement only when required because it is inflexible and should be used only when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently processed element.
Octocat - CodedBug github
To refer more examples on this topic refer codedbug GitHub repo 

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?