Apps/Gaming

Java WHILE and DO WHILE loops

Looping is a feature of programming languages ​​that facilitates the execution of a set of instructions repeatedly while some condition is true. Java provides no less than three ways of executing loops. While all of them provide similar basic functionality, they differ in their syntax and condition evaluation.

This programming tutorial will focus on Java’s while loop and it’s cousin, the do while loop, which are two of the most basic and oldest looping constructs. They are also extremely well supported, appearing with virtually the exact same syntax in programming languages ​​like C, C#, Objective-C, C++, JavaScript/TypeScript, and, of course, Java.

Reading: How to Use Java Foreach Loops

What is the While Loop in Java?

the while construct consists of two parts: a condition/expression and a block of code. First, the condition/expression is evaluated; if the condition/expression is true, the code within the block is executed. This repeats until the condition/expression becomes false. Because the while loop checks the condition/expression before the block is executed, this control structure is often referred to as a pre-test loop.

Here is the syntax of the while loop in java:

while (boolean condition) { loop statements… }

The Steps of While Loop Execution

A while loop typically contains certain steps that can be depicted as a flow diagram, as depicted in the image below:

Here’s an explanation of each step in the above diagram:

  • Initialization condition (the black circle): Here, we initialize the variables in use. It marks the start of the loop. A previously declared variable can be reused or a new variable can be declared that is local to the loop.
  • Test condition (A): Used for testing the exit condition for a loop. The expression must return a boolean value. the while loop is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  • Statement execution (B): Once the condition is evaluated to truethe statements in the loop body are executed.
  • Increment/Decrement (B): Variables must be updated before the next iteration; otherwise, an infinite loop (a loop with no exit that infinitely repeats itself) could result.
  • Loop termination (the black circle with an outer border): When the condition becomes falsethe loop terminates, thus marking the end of its life cycle.

Java WHILE loop code example

in Java, while loops are a great way to generate a series of numbers, say from 1 to 10which is exactly what the class in our while loop example code below does:

import java.io.*; class NumberSeriesGenerator { public static void main (String[] args) { int i=1; while (i<-10) { System.out.println(i++); } } }

Java while loop tutorial

Reading: Top Java Online Training Courses and Bundles

The While-true Loop and Breaks in Java

Breaks are often useful for exiting while loops prematurely. Breaks are often a feature of while true loops, which use a true literal in place of a condition so that the loop is terminated by one or more break statements, rather than the testing condition. Here is an example of how to use a while true loop in java:

import javalang.Math; public class WhileTrueLoop { public static vid main(String[] args) { // Loop infinitely. while (true) { //Get random number between 0 and 1. double value = Math.random(); System.out.println(value); // Break if greater tan 0.8. if (value >= 0.8) { break; } } } }

While true loop in Java

Employing a while true loop in conjunction with a break is considered to be a bad practice because it can almost always be rewritten as a “while condition” loop, which improves readability and maintainability.

In this case, we can rewrite the class by initializing the double value before the condition evaluation and then reversing the condition so that we loop while the value is less than 0.8. Here is the updated class:

import javalang.Math; public class LoopWhile{ public static vid main(String[] args) { // Initialize value so that we enter the loop double value = 0.0d; // Loop while value is less than 0.8. while (value < 0.8) { // Get random number between 0 and 1. value = Math.random(); System.out.println(value); } } }

Java loop while

Java Do While Loop

As mentioned previously, the control structure of the while loop is often referred to as a pre-test loop because it checks the condition/expression before the block is executed. In situations where we always want to execute the code block at least once, we can employ the do while loop. Java’s do while loop is a variant of the while loop that executes the code block once, before checking if the condition is true. It will then repeat the loop as long as the condition is true.

Here is the syntax for the do while loop in java:

do { statement(s) } while (expression);

In our last example we initialized the double value to 0 in order to satisfy the loop condition. Utilizing a do while loop instead saves developers from having to worry about the double value’s initialization value since it no longer prevents the code block from executing:

import java.lang.Math; public class LoopWhile { public static void main(String[] args) { // Initialize value so that we enter the loop double value = 0.0d; // Loop while value less than 0.8. do { // Get random number between 0 and 1. value = Math.random(); System.out.println(value); } while (value < 0.8); } }

Do While Loop in Java


Reading:
Java Tools to Increase Productivity

Nested Loops in Java

A nested loop refers to a loop statement residing inside of another loop statement. Nested loops may be made up of different combinations of loop structures, including while loops and do while loops.

The following Java code example utilizes nested while loops to generate numeric triplets:

import java.io.*; class GenerateNumberTriplets { public static void main(String[] args) { int = 1, j = 1; while (i++ <= 3) { while (j <= 3) { System.out.println(""); j = 1; } } }

Java nested while loop

This next program employs a total of 3 do while loops to produce numbers from 1 to 5 in a tabular format:

import java.io.*; class GenerateTabularNumbers { public static void main(String[] args) { int row = 1, column = 1, x; do { x = 4; do { System.out.print(“”); x–; } while (x >= row); column = 1; do { System.out.print(column + ” “); column++; } while (column <= 5); System.out.println(" "); row++; } while (row <= 5); } }

Java nested do while loop

Final Thoughts on the Java While Loop

In this tutorial, we learned all about the while Loop (and it’s cousin, the do while loop), which is one of the most basic and oldest looping constructs. When coding your loops, just be careful that the condition will always eventually evaluate to true; otherwise, you will have yourself a runaway code block, otherwise known as an infinite loop. We also learned how to nest our loops as well.

In the next installation on Java Loops, we will be covering the Java for loop, which is the ideal choice when you know exactly how many times you want to loop through a block of code.

Related posts

Best Practices for Multithreading in Java

TechLifely

How to Use LaTeX for Technical Writing

TechLifely

Type Conversion in Java

TechLifely

Leave a Comment