Learn about For, While and Do-While Loops in Java Programming

0
2993
Java (8) - Loops-3

Java (8) - Loops-3

When you want to repeat the same statement, or block of statements, a specific number of times, or indefinitely, you use loops. Java offers the following types of loops: for, while, and do-while.

For loops
They are used when you know the number of times you want your code to run. For example, suppose you want to display the phrase “Hello World” 5 times. You’d write code like the following:

The output is:

Let’s analyze the structure of this loop:

  1. Starts with the for This instructs the compiler that you want to run a for loop.
  2. Inside the parentheses, you initialize the variable that will be used for iteration, i in our case. You can initialize it to any value you wish, not necessarily zero.
  3. The second part is the loop condition. This instructs the compiler when to end the loop. In our case, as long as i does not reach 5, continue the loop.
  4. The last part is the command that updates the loop variable. In the example, it is incrementing the variable with 1 on each iteration.

The loop definition parts must be separated by semicolons.

While loop
Here you don’t have an idea about the exact number of times the loop will run. But you do have a condition that you want the loop to run as long as it is valid. A very common use of such a loop is when you want the user to enter specific text. You want the application to display the instruction message to the user as long as the correct text is not entered. Consider the following example:

If you run this code, you will see the following prompt:

If you pressed any character other than y or Y the message will appear again. It will continue to appear as long as you do not enter the expected character: y or Y.

The while loop starts by the keyword while followed by the loop condition in parentheses. You can add whatever statement as a loop condition as long as it resolves to Boolean True or False. In the example, we are testing for the value of the variable answer. It is initialized by 0 then updated by the value the user enters. On each iteration of the loop, this variable is examined: if it is not equal to “Y” or “y”, the loop continues execution of its body, which contains code to display the instruction message to the user. Only when “y” or “Y” is entered does the loop exit.

Side note

You may have noticed in this example that we have used an integer type of variable (int) to compare a character type (char). Actually, Java treats the char type internally as an integers. Characters are defined in what is called “character tables”. ASCII and UNICODE are among the most important types of those tables. In a character table, each letter is mapped to a number. The computer uses this mapping to display the correct character. UNICODE table was created to absorb the huge number of characters that can be found not only in English but in all world languages. You can read more about this in this Wikipedia article: https://en.wikipedia.org/wiki/Unicode

Do-while loops
Perhaps the major aspect of this type of loops is that the loop is guaranteed to run at least once, even if the condition that keeps it going is false. The following example will give you a clearer look:

In this loop, although the condition is clearly not met (i == 0 while the loop requires it to be > 0), the text is printed to the screen one time.

The structure of the loop is simple: you start with a do keyword followed by a block of statements (loop body) enclosed in curly braces. Then you specify the resume condition in brackets preceded by the while keyword.

Java Programming Course for Beginner From Scratch

The continue keyword
Sometimes you find that you have to exit a loop iteration prematurely (before completion). A typical scenario is when you are copying a large number of files from one directory to another. You are not sure that all the files will be copied. There may be permission errors for example. You don’t want the execution to stop because 1 file has permission errors. Instead, you want to continue the operation, and log this permission error somewhere so that you can fix the problem later. For the sake of simplicity, we’ll modify this scenario slightly to make the target is to copy the first and the third files, whose names are contained in an array. In other words, if the file to be copied is the second one, skip it. Consider the following example:

The output of this code will be:

File2 has been skipped from the copying process. In a real world application, you’d replace the code in filecopy function with code that does actually file copy. Have a look at the condition we put right at the start of the loop body: if you find that the file you are about to copy is file2, continue. And continue instructs the loop to skip the remaining code, and perform the next iteration directly.

Infinite loops
At first thought you say: when will I ever need a loop that will never stop? Well, a possible scenario for this is when you build daemons. A daemon is simply a program that works in the background, it typically has no user interface at all. For example, a network daemon that logs messages received from clients in a file or database. This daemon will have to be running in the background, listening for incoming connections, and taking the appropriate action(s) when it receives one. For an application of this type, an infinite loop has to be created, because you want the application to remain running till it is manually terminated.

To make a loop run infinitely, you use the Boolean True for while and do-while loops. Consider the following example:

And the do-while one:

But you have to be a little careful when you write code like the above. An unintentional infinite loop in your code is one of the hard-to-discover bugs. Create an infinite loop only as needed.

Summary
By completing loops, we have completed the basic language structures. Now let’s move to some more advanced topics. In the next article and the ones following it, we will start discussing object oriented programming in Java. So, stay here; more interesting topics are on the way.

LEAVE A REPLY

Please enter your comment!
Please enter your name here