Java Loop | For Loop Java | While and Do-While Loop

A Java loop works in a weird way. When I saw one for the first time, I was surprised why would anyone make for loop java to be so bizarre in the first place. Then when I actually worked on it, I realized it wasn’t really that bad. All I had to do was remember syntaxes for Java loops and things began to look up.

Loops in Java are great when you want a repetitive activity to be carried out till a condition is met. They fall under the control statements category since they let you control the order of execution based on a logic you specify. To get a hang of other control statements you can visit the if else chapter.

java loop image meme

What are loops if not something that repeats ?

All in all there are three major iteration control statements that Java brings to use:

  1. For Loop
  2. While
  3. Do While

We are going to tap into each Java loop Iteration statements one by one.

What is For Loop in Java?

This comes from the collection of Java loop which is regularly brought into use to tackle various scenarios. For loop works great when you need to repeat a statement till a condition is true. That being said it is a repetition control structure that banks on increment and decrement scenario to reiterate a certain code.

There are actually three types of For Loop Java.

They are namely:

  • Simple for Loop
  • For Each or Enhanced For Loop
  • Labeled For Loop

Simple For Java Loop

This one comes straight from previous languages like C and C++. So, if you have worked on those languages before, you already how to write a simple for loop. Even if you haven’t, understanding this wouldn’t take you long.

Like I said before just remember the syntax for Java Loop and things are going to be fine.

The syntax to remember here is:

for (initialization; condition; increment/decrement) {

----stuff-----
}

Now the order in which things get executed basically defines how you gotta learn about a ‘for loop’. Here’s the initialization is the first thing that your JVM looks for, and then the condition that you wish to execute your stuff for. Then as soon as the condition is met, it enters into the braces where you wish to execute your ‘stuff’. The control then goes back to increment/decrement the moment your stuff is executed, and then revisits the condition to see if it is still being met.

Confusing? We will feed this into an example to understand.

for loop example java loop

Now the first thing the JVM’s gonna do is enter your main method, and head straight to the first statement that is about initializing j to 10. As soon as it encounters the for loop Java it executes the initialization part. When i is initialized to 0, it heads straight to check the condition.

The condition i < j meaning 0 < 10 holds good, so it will head straight to your stuff, which is trying to display the value of i.

After displaying 0, it will go to the third sector, of increment/decrement, where i ++ insinuates increasing i by 1.

NOTE: i ++ means i = i + 1

So now your i has become 1.

It will go back to check the condition of i < j which still holds good with 1 < 10, and thus moving on to display the value of i. which is 1 this time, and so on.

The output you will get would be:

image to display result of for loop in java

Easy right?

Moving on to check the second type.

For Each or Enhanced For Loop

For Each is generally used to work with arrays or Collections in Java. The latter is something we will see later. It is in a way better than simple Java loop, since we don’t have to increment the value here.

The syntax we need to remember here is:

for (Type variable: array) {

----stuff----

}

So when you are trying to read this, it should say “for each variable in array do (stuff)!”

The enhanced for loop deals with elements inside the array and not the index, and hence it will always return what is inside those elemental spots.

An example would, of course, make things better:

for each example java

Now here I have simply created a new array j with type int to point to some values. Now using for each loop I am saying – “For each i in Array j display the value of i” meaning display everything that is inside those elemental slots.

The result would show you what j[] array holds.

image to display result of for loop in java

The third type of For Loop Java is the Java Labeled For Loop.

Labeled  For Loop

Did you know that we can label our for loops too? Yes, it’s possible!

To do that you just need to use a label name before your for loop.

So the syntax would become fairly easy to remember:

labelname:

for(initialization; condition; increment/decrement) {

----stuff----

}

It is great when you are working with multiple nested loops.

How to exit from for loop in Java

We can use break or continue keywords to either get out of the loop or continue it as per our disposition.

NOTE: Remember using break/continue generally affects the innermost for loop only by default.

Here’s an example:

labeled for loop example

Notice how break Outer has been used to deliberately escape from the outermost loop to end the program right then and there. Breaks come in handy when you wish to get out of a loopy situation.

The above program will give the following result:

result of a labeled for java program

Using break Inner wouldn’t have been helpful here, since it is an inbred quality of a loop to get out of its loop when its condition is not met.

Okay there’s one more For Loop known as the infinitive loop which is used when you wish to

Infinitive Loop

If you use the following syntax:

for(;;) {

---stuff---

}

running your program is going to send you flinging in an infinitive loop.

Jeez, Why would anyone really wanna go in an infinitive loop?

The only escape out of it would be to press Ctrl + C. If you are working on Eclipse you can right click and Terminate too. Or you can press the red button (for terminate) too.

Here’s an example:

an example of infinitive loop in java

While Loop Java

Moving on to the second crucial looping system in Iteration Statements in Java.

While Loop Java is still one of the most preferred ways when it comes to executing a block of code till a condition is met. It’s syntax is short and sweet and is perfect for laymen like us:

while(condition) {

---- stuff to be executed -----

}

The control here starts from the condition, executes whatever is inside the braces and then goes back to the condition to check if it is still being met. This keeps on going till the condition is no longer met, after which the loop is exited.

Here’s an example to make things crystal clear:

example of while loop

The output to the above would be fairly simple as we have seen before with the simple for loop Java example:

0
1
2
3
4
5
6
7
8
9

Java Infinitive While Loop

You can make the while loop infinitive too. The syntax to do that would be:

while (true) {

----- stuff to execute -----

}

Well, that makes sense. If your condition is always true the loop is going to keep on going. We will quickly check an example before moving on to the last topic:

while infinitive loop example in java

Do While Java

There could be times when you realize that the number of iteration in your control statement program is not fixed. During such times do while Java comes to the rescue.

It is used to iterate a part of the program several times.

NOTE: The stuff inside the do while Java loop is executed at least once since the condition to be checked is located after the loop body.

Here’s the syntax of do-while Java loop:

do {

---- stuff to execute ----

} while (condition);

Examples make things better they say:

do while loop java example

Running the above program will give you the same result we have been getting so far:

0
1
2
3
4
5
6
7
8
9

Do While Infinitive

Getting an infinitive here wouldn’t be difficult either. You just have to make the condition always true. So, the Java loop will end up becoming infinitive in nature.

A good example would be:

do while infinitive loop

To knock it off just press the red termination button.

That’s all we have in this chapter. Make ’em all count.

Do something fruitful while you have time.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

2 Responses

  1. May 15, 2017

    […] had earlier mentioned one good example of using a foreach or enhanced for loop to display elements in an array. Do check it […]

  2. June 27, 2017

    […] through a collection is nowadays being performed using for-each styled for loop or enhanced for loop. An example you will see soon […]

Leave a Reply