Looping in Java

Looping in Java

Well, at times, it happens that there is some code, which is needed to be executed a number of times. For example, just imagine that you want to print hello 15 times, or maybe 100 times or even more. One thing that you can do is just write the instruction for printing hello once, and then paste it a number of times as per the requirement. We had just one instruction to execute here a number of times.

What if there are such 100 instructions, which are to be executed a number of times? What are we going to do in such a situation? Do we have anything better that saves us?

Looping in Java

Well, yes… looping is our escape. You can consider that whatever you wish to execute repeatedly for a number of times (like the instruction to print hello), you can put it inside a loop. You can consider the example of the washing machine.

We can wash our clothes manually, one by one. But this is a repeated task, in which we are going to get the cloth and wash it, then get the next cloth and then repeat the same thing, and then again the same thing. But you are done when the clothes are finished. But is anything better we can do here? Yes, we can use a washing machine, with which we can put all the clothes that we need to wash, and just do some settings, and just let the washing machine do the rest of the work.

We have a lot more examples considering looping in mind, which may not relate directly but are good often for understanding the concept and relating it with programming. We sometimes like a song which is playing on our music player. We choose to put that song in the loop, and now we have only that song running, and we vibe on the song. Well, there are many other areas where the concept of looping is being used in some form and for some cause.

So, let’s now begin understanding and using different loops in java. We will go through the details like syntax, examples, and how can we use them. We have got some types of loops here, like for loop, while loop, do… while loop, which we are going to explore one by one now. Understand that basically, all the loops are meant for looping. We will observe some differences in syntax and a little in functionality as well.