• Skip to main content
  • Skip to primary sidebar

Technical Notes Of
Ehi Kioya

Technical Notes Of Ehi Kioya

  • About
  • Contact
MENUMENU
  • Blog Home
  • AWS, Azure, Cloud
  • Backend (Server-Side)
  • Frontend (Client-Side)
  • SharePoint
  • Tools & Resources
    • CM/IN Ruler
    • URL Decoder
    • Text Hasher
    • Word Count
    • IP Lookup
  • Linux & Servers
  • Zero Code Tech
  • WordPress
  • Musings
  • More
    Categories
    • Cloud
    • Server-Side
    • Front-End
    • SharePoint
    • Tools
    • Linux
    • Zero Code
    • WordPress
    • Musings
Home » Programming » Java » Working With The Different Types Of Loops In Java

Working With The Different Types Of Loops In Java

By Ehi Kioya 2 Comments

Loops are arguably some of the most important features in any programming language and if you’re just starting to learn to code, they are going to be among the first hurdles you will need to overcome. And the fact that there are different types of loops just adds to beginner confusion.

This article will walk you through the different types of loops in Java. And I will provide working examples in each case.

While loops may be tricky for beginner developers, the good news is that, looping structures are very similar in different programming languages.

So, if you understand the different types of loops in Java, you shouldn’t have much trouble implementing similar looping structures in any other object oriented programming language. The internal logic is often the same and you will probably just need to figure out the loop syntax used in the particular programming language you’re working with. And as I like to say…

Syntax is hardly ever the bottleneck.

What Are Loops?

Basically, loops are control statements. They allow us to maneuver a program’s flow into different directions that are otherwise linear.

With loops, you can repeat a process for a while, forever, or until some specified condition is met.

Types Of Loops In Java

There are 3 basic types of loops in Java:

  • The for loop,
  • The while loop, and
  • The do while loop.

Each of these loop structures allow programmers to control the execution flow of a program by performing a set of statements repeatedly as long as a defined condition continues to be true.

The code inside both the for and while loops are executed zero or more times. Execution stops if the loop continuation condition is false. In contrast, the do while loop executes the code in its body one or more times.

So, a do while loop code body always gets executed at least once – regardless of the looping continuation condition.

Common Structure Of Java Loops

All loops in Java share this common structure:

  • They have a control variable – known as the loop counter.
  • The loop counter must have an initial value – it must be “initialized”.
  • On each iteration of the loop, the value of the control variable (loop counter) either gets incremented or decremented.
  • All loops have a loop condition which determines if looping should continue or not.

Interestingly, the differences between the 3 loop types are merely syntactic. If we want to, we can quite easily replace one type of loop with another type (we just need to tweak the condition/structure a little) and still get the same results. I guess, different types of loops are made available in programming languages primarily to satisfy developers’ needs for convenience and choice.

Personally, I hardly ever use the do while loop myself even though in hindsight, there are quite a lot of situations where it could have come in handy.

Let’s investigate each of these looping structures individually and then compare them against each other.

The while Loop

The while loop lets us execute a statement (or a block of code) repeatedly until the loop condition is false – or “while” the condition remains true.

For example, say we want to print all consecutive even numbers from 1 to 20. To do this using a while loop, we first define and initialize our loop counter variable outside the while loop. Then we state our loop continuation condition. And then, somewhere inside the loop, we increment the loop counter control variable so that at some point during the loop’s iteration, the condition will become false and program execution will break out of the repetition.

Here’s the code for the above example:

// Define and initialize the loop counter control variable.
// We start testing (counting up) from 1.
int counter = 1;

// Notice the loop continuation condition.
// Our limit is 20 so we're checking if our counter is less than or equal to 20.
while (counter <= 20)
{
	// Now we check if the number is divisible by 2 using modulo (%).
	// If the number is divisible by 2, it is even.
	if (counter % 2 == 0)
	{
		System.out.println(counter);
	}
	
	// Finally, we increment the loop counter.
	counter++;
}

Before the program even reaches the while loop, it first finds the variable named counter and initialized to 1.

When the program first encounters the while loop condition, it evaluates to true because the value of the counter variable is 1 (and 1 is less than 20). The program then enters the body of the while loop and evaluates the statements in there. In this case, it tests if the value of the counter variable is even (by checking if it is divisible by 2). On the first iteration of this program, the println command will not be executed because 1 is not divisible by 2. The program goes ahead to increment the counter to its next value and rebounds back to the while loop condition to repeat the test. On the second iteration, the number “2” gets printed out because all the conditions are met. The program again increments the counter to its next value… and so on.

At some point in the loop iteration, the value of the counter will be 21, which is greater than 20, and the loop condition will evaluate to false. At this point, program execution will break out of the loop.

Based on the above logic, if we were to write a while loop like this:

while (true)
{
	// Some code here...
}

Then whatever code is written in place of “Some code here…” will be repeatedly executed forever (or until the program is interrupted). Because the loop condition is always true.

Same thing will happen if you write this code:

int counter = 1;

while (counter <= 20)
{
	// Some code here...
	counter--;
}

This time, the condition will always remain true because the counter variable is decremented (and so will always be less than 20).

Infinite loops like the above are common mistakes in programming and depending on the code complexity, they may not always be easy to detect. However, it is a programmer’s responsibility to ensure that their code doesn’t hang up in an infinite loop.

If we start the loop with a false condition like this:

while (false)
{
	// Some code here...
}

The code block within the loop will never get executed since the initial condition wasn’t met.

The for Loop

The for loop is very similar to the while in how it works. The difference is that with the for loop, the control variable, the loop continuation condition, and the increment (or decrement) of the control variable can all be stated on a single line of code.

Let’s rewrite the code for printing all consecutive even numbers from 1 to 20. But this time, we will use a for loop. Here goes…

for (int counter = 1; counter <= 20; counter++)
{
	if (counter % 2 == 0)
	{
		System.out.println(counter);
	}
}

True, I have removed the comments earlier added. But you can still notice that the for structure looks shorter than that of the while loop. for loops save us some extra lines of code by allowing us control everything in one line.

This, I believe, is probably why the for loop (or enhanced versions of it) is the most widely used loop structure in pretty much any programming language.

You can also write different variations of for loop code.

So for example, the for loop structure can also be written like this:

int counter;
for (counter = 1; counter <= 20; counter++)
{
	// Some code here...
}

Or like this:

int counter = 1;
for (; counter <= 20; counter++)
{
	// Some code here...
}

Or even like this:

int counter = 1;
for (; counter <= 20;)
{
	// Some code here...
	 counter++;
}

But by far the most popular structure is the first one above that puts the entire loop control in a single line of code in this format:

for(<initialization>;<condition>;<increment/decrement>)
{
	// Code here...
}

One thing to note about the different for loop structures above is that when the control variable (loop counter) is declared in the for loop header, the control variable will not exist outside the loop. It is scoped within the loop only. However, when the control variable is declared outside/before the loop, it exists both outside and within the for loop.

Here’s an example of a single line, infinite for loop:

for(;true;);

Cool, eh?

Here’s an even shorter one:

for(;;);

Isn’t code such a beautiful thing?

Comparing while And for Loops

Both while and for loops are “entry controlled”. They first evaluate the truth of a condition and only execute the loop body when the condition is true.

So you can easily substitute for loops with while loops. And vice-versa.

Of course, they remain syntactically different. So while this may be a valid infinite for loop:

for(;;);

This attempt at an infinite while loop produces a syntax error:

while();

If you want a loop that does not evaluate the truth of a condition at its entry, you should consider the do while loop.

The do while Loop

The do while loop is “exit controlled” (as opposed to the “entry controlled” looping structures discussed above).

The code body of a do while loop will always get executed at least once. No condition is evaluated the first time.

The do while loop is however, quite similar to the while loop in its structure – the control variable is initialized outside/before the loop header, and the incrementing or decrementing of the control variable is performed within the loop body.

Here’s how our even number printing code looks in do while loop format:

int counter = 1;

do
{
	if (counter % 2 == 0)
	{
		System.out.println(counter);
	}
	counter++;
}
while(counter <= 20);

for and while loops are designed to be executed zero or more times. This means that they may not execute at all if the initial condition evaluates to false. But do while loops always executes one or more times because it does not check any condition during its entry.

Coding Convention When Working With do while Loops

If you have only one line of code within the body of a while loop or a do while loop, it is not mandatory to wrap the single line of code with braces. However, for do while loops particularly, it is recommended (and conventional) to still wrap a single line of loop body code with braces.

The reason for this is to avoid confusing the “while” portion of a do while loop with an independent while loop.

Using braces makes do while loops easy to read and maintain.

The Enhanced Java for Loop

There’s technically a fourth kind of looping structure in Java – the enhanced for loop. It is meant solely for iterating through an array or a class that implements Iterable. I haven’t discussed it in detail here because with a good knowledge of the above 3 basic looping structures, the rest is easy stuff.

Found this article valuable? Want to show your appreciation? Here are some options:

  1. Spread the word! Use these buttons to share this link on your favorite social media sites.
  2. Help me share this on . . .

    • Facebook
    • Twitter
    • LinkedIn
    • Reddit
    • Tumblr
    • Pinterest
    • Pocket
    • Telegram
    • WhatsApp
    • Skype
  3. Sign up to join my audience and receive email notifications when I publish new content.
  4. Contribute by adding a comment using the comments section below.
  5. Follow me on Twitter, LinkedIn, and Facebook.

Related

Filed Under: Backend (Server-Side), Java, Programming Tagged With: Eclipse, Java, Looping, Programming

About Ehi Kioya

I am a Toronto-based Software Engineer. I run this website as part hobby and part business.

To share your thoughts or get help with any of my posts, please drop a comment at the appropriate link.

You can contact me using the form on this page. I'm also on Twitter, LinkedIn, and Facebook.

Reader Interactions

Comments

  1. Kenneth Atisele says

    February 24, 2020 at 3:29 pm

    Hello Ehi,

    I am a big fan and I love your post. Also I intend to take up programming as I lost track at some point in my career (I went into sales).
    I remember I had an intermediate knowledge of VB6 where packages were bundled into setup files and then installed on stand alone systems.
    Well that’s a long time ago. I want to take it up again and see how well i can improve.
    Can you be my mentor? And which package do you advise I start with – Rails, Python, C++, whatever as long as you will be the guide…i will be a loyal student.

    Trust I will hear from you soon.

    Sincerely,

    KEN

    Reply
    • Ehi Kioya says

      February 24, 2020 at 5:19 pm

      Hi Ken,

      I’ll be happy to help where I can. If I had to recommend something for you based on the 3 options you mentioned (Rails, Python, and C++), I would say go with Python. Note though, that Rails is a framework and not a programming language in and of itself (Ruby is the language upon which the Rails framework is based). So, your three options are not exactly “apples to apples”. But I think I would still recommend Python regardless.

      To help you get started with Python, you might want to join our forums and follow the work of some of the Python professionals on there. Lots of in-depth Python training material is being posted on the forums almost daily. Specifically, you might want to follow the work of these guys: @idowu, @oluwole, and @simileoluwa. I manage the entire team, and if you ask a question and mention me using my handle @ehi-kioya, I will get notified.

      On a slightly different note, you might be happy to learn that even though packaging and deployment, and the creation of setup files may sound so old school, it is very NOT dead. I wrote a huge article about one such application setup package tool (NSIS) not so long ago. Generally, you won’t hear about that type of programming as much as you would hear about fancy web frameworks like ReactJS, or any of the new tooling used in web development these days. That’s because, people who build such applications are just different types of programmers (not web developers). Data science, which is another hot area of programming these days also doesn’t care much about application setup packages.

      Even though I just recommended Python for you, your final decision about which programming language to start with should depend on what sort of software developer you want to become. Are you trying to learn web development? Is your final goal full-stack development? Do you want to be a mobile guy? Or would you like to become a data scientist? Do you already know VB so well that it might make sense to stick with the Microsoft ecosystem and do .NET stuff (VB.Net, C#, .Net core, etc.)?

      These questions can help guide your decision. To be fair, Python would only really shine if you have interest in data science. If you would rather be a web or mobile guy, or if you have dreams of becoming a full-stack developer someday, it might be a better idea to start with JavaScript, JavaScript frameworks, and the NodeJS ecosystem (blog link and forum link).

      Anyways, hope all that rant helps guide you a little. I wish you the best in your learning process. Don’t hesitate to ask me further questions.

      Cheers!

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

23,569
Followers
Follow
30,000
Connections
Connect
14,568
Page Fans
Like
  • Recently   Popular   Posts   &   Pages
  • Actual Size Online Ruler Actual Size Online Ruler
    I created this page to measure your screen resolution and produce an online ruler of actual size. It's powered with JavaScript and HTML5.
  • How To Install PHP Packages Without Composer How To Install PHP Packages Without Composer
    This article shows how to bypass the Composer barrier when installing Composer-dependent PHP packages. Great shortcut for PHP enthusiasts!
  • Fix For “Function create_function() is deprecated” In PHP 7.2 Fix For "Function create_function() is deprecated" In PHP 7.2
    As of PHP 7.2 create_function() has been deprecated because it uses eval(). You should replace it with an anonymous function instead.
  • About
  • Contact

© 2022   ·   Ehi Kioya   ·   All Rights Reserved
Privacy Policy