This is the fourth lecture of the Learn Java lecture series. In this you’ll learn about loops in Java. We will be working with while loop, do-while loop and for loop in java.

Let’s make a new class and call it Loops.

newly created class in java

In the Learn Java Variables lecture we saw a variable type boolean. So let’s create a  boolean:

Now this is a good time to do somethings with bool like:


While Loop:

While loop in java is written in while(condition) {…Do work inside the loop here…} format. Here is an example of while loop in which we have an int and a boolean and we are applying conditioning based on it.

For your practice remove the boolean and just apply the conditioning based on int only. I’ve used both int and boolean just to clarify that how both things can be used. Run the code and you’ll see this output:

output of a java program with while loop

Do-While Loop:

Do-while loop is the same as while loop but the only difference is that the code will run at least once. Here is the syntax of do while:

do {…lines of code to be executed…} while(condition);

So as you can see the do block will run and the it’ll check for the condition. So at-least once the code in the block will execute.

For Loop:

The format of for loop is almost same if you see the sudo. It start with the keyword for(;;){..code inside the loop…} and that’s it. However the conditions in a for loop are different as you can see I’ve placed two semi-colons in the brackets. Here is how you do it:

Here is the output:

output of for loop java

Let’s change the print statement with format specifier. Not that println means print in a new line but in this new method we are going to user printf which for ease you can remember it as print forward. Printf dose not print in a new line automatically.

%d is a format specifier to print integer value and \n is used for new line. Now remember if you need to use format specifier you should use printf and not println.

Tags : do while loop in javafor loop in javaswitch statement in javawhile loop in java
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.