Java Basics Tutorial – Part 8 – While Loops

Share on facebook
Share on twitter
Share on linkedin
In this part of the Java Bascics Tutorial, we take a look at While Loops.

In this lesson, we continue with the Java Basics Tutorial. That is the eighth part of this series, and if you want to see the complete list of lessons, you can do it here. If you are not familiar with For Loops, you can see our previous article about them here.

A While Loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The While Loop can be thought of as a repeating if statement.

 

In the expression, we have to test the condition. If the condition evaluates to true, then we will execute the body of the loop and go to update the expression. After executing the loop body, this expression increments/decrements the loop variable by some value. Otherwise, we will exit from the While Loop.

How does While Loop execute?

  1. Control falls into the While Loop.
  2. The flow jumps to the condition
  3. The condition is tested.
    1. If it is true, the flow goes into the body.
    2. If it is false, the flow goes outside the loop
  4. The statements inside the body of the loop get executed.
  5. The update takes place.
  6. Control flows back to Step 2.

One more thing, which we have already read in the previous article about advanced conditional statements, is the break statement. It ends the loop immediately when it is encountered. The break statement is usually used with a conditional statement inside the loop.

Both While and For Loops repeat a block of code. We use For Loops when we preliminary know the number of iterations. If we don’t know when the exit condition will be met, we use While Loops.

Lesson Topics

In this video we review the following topics:
  • While Loops
  • While or For Loop?
  • Operator Break
  • Infinite Loops

Remember that coding is a skill, which should be practiced. To learn to code, you should write code every day for a long time. Watching tutorials is not enough. You should code! 

We would love to hear from you, so leave a comment below saying what topics you would like to see next. 

Register now and take your free resources right away! You will get access to automated exercises which will sharpen your coding skills. You will become a member of the SoftUni Global Community and we will provide you the opportunity to communicate with other students and mentors and get help for FREE.

Leave a Comment

Scroll to Top
small_c_popup.png

Sign in

Don’t have an account? Register with us to join the community.