What are Loops in Java?
To begin with, let’s figure out what a loop is. A loop is any repeating action.
For example, every morning, you:
- get up
- go to the bathroom, brush your teeth, and shave your face or legs
- open the fridge and eat everything at hand
- get dressed
- go to work or college
So, at least 5 times a week (Monday-Friday), you perform the same sequence of actions. And if the sequence of actions is the same, then we are talking about a loop. So now you know what a loop is.
In Java, there are 4 loop types:
- the "while" loop
- the "do…while" loop
- the "for" loop
- the "for each" loop
At this stage, it will be enough for you to know only the first three loop types.
We will take a look at the "for each" loop a little bit later in another article. For now, all you need to know is that the "for each" loop is a variation of the "for" loop. The "for each" loop only appeared for the first time in JDK5. In earlier versions of JDK, it didn’t exist.
So it’s high time to learn about the "while" loop.
The While Loop
This loop is sometimes called the "as long as” loop.
Let’s start with a somewhat funny, fictional everyday example.
Let’s say you have a friend called Charlie and he has a girlfriend called Katie. They are in the “rose and candy stage” - you know what that means. Charlie gives her flowers, invites her to restaurants, and buys her ice cream. In short, he's romancing her.
But Charlie has a limited budget. So he tells himself: “I will invite Katie to restaurants and give her flowers as long as I have at least $10 in my wallet. But as soon as I see that I have less than $10, it will all be over; we will conclude the “rose and candy stage” and, instead, we will just sit on the couch at home and watch TV and so on."
If you describe this life situation using the while loop (remember, sometimes the while loop is called the “as long as” loop), it will look as follows:
1 2 3 4 |
while ( int the wallet > = $10 ) { buy ice cream for girlfriend; give her flowers; } |
In the example above:
- While is "as long as"
- (in the wallet > = 10$) is the condition
- “buy ice cream for girlfriend”, “give flowers” – these are the actions which will be performed as long as the condition is true.
So, the general form of a while loop in Java looks as follows:
1 2 3 |
while (condition) { // actions } |
Remember, the essence of the while statement is that it repeats the action(s) as long as the condition is true. That means, as long as Charlie has > = 10$, he will buy ice ice cream for his girlfriend and give her flowers. When the condition Charlie has > = 10$ becomes false, the repetition of the actions “buy ice ice cream for girlfriend” and “give her flowers” will stop and the loop will be completed.
It’s time to try to write a Java code using the while loop.
Task No. 1
It’s necessary to display the numbers from 1 through 7, i.e. we should see the following on the screen: 1 2 3 4 5 6 7
Solution:
1 2 3 4 5 6 7 8 9 10 |
class Test{ public static void main(String args[]){ int i = 1; while (i < 8) { System.out.print(i + " "); i++; } } } |
Task No. 2
But if we write the code this way, it won't be performed.
1 2 3 4 5 6 7 8 9 10 |
class Test { public static void main(String args[]) { int i = 1; while (i < 0) { System.out.print(i + " "); i++; } } } |
Why? Because the initial value is "int i =1", but we wrote "while (i <o)" in the condition. The i variable already equals 1, and therefore i can't be less than 0. Consequently, the code can't be executed even once.
Task No. 3
And if we wrote the code in the following way, the list of numbers would go on infinitely (1 2 3 4 5 6 7 …)
1 2 3 4 5 6 7 8 9 10 |
class Test { public static void main(String [args]) { int i = 1; while (true) { System.out.print(i + " "); i++; } } } |
This is an example of a so-called infinite loop, because the numbers will be displayed to infinity *1 2 3 4 5 6 7 8 9 10 11 12 13 …) If you already ran this code on your computer, then you noticed that the program was blocked by the infinite loop, because the code wouldn’t stop; instead it would just continue displaying numbers on the screen. To get out of such a situation, you need to press the keyboard shortcut Alt + F4.
Why are the numbers displayed to infinity? Well, because we wrote "while (true)" in the code. And since the condition will always be true, the numbers will display endlessly.
Task No. 4
It’s necessary to display the following number sequence on the screen:
100 90 80 70 60 50 40 30 20 10
Solution:
1 2 3 4 5 6 7 8 9 10 |
class Test { public static void main(String args[]) { int i = 100; while ( i > = 10){ System.out.println( “Countdown:” + i); i-=10; } } } |
Commentary:
"i-=10;" is shorthand for "i = (i-10);"
Here you can find more examples of while loop tasks.
Do…while loop
The do…while loop is one of the variations of the while loop. To understand the difference between do…while and while loops, let’s compare two examples of code.
Task No. 5 – code with the while loop
1 2 3 4 5 6 7 8 9 10 |
class Example1 { public static void main(String args[]) { int i = 1; while (i < 0) { i++; System.out.print(i + " "); } } } |
Commentary: this code won’t be executed. This is because the condition "while ( i < 0 )" is checked, and the code executes only if the condition is true. i.e. the while loop pre-checks the condition.
Task No. 6 – code with the do…while loop
1 2 3 4 5 6 7 8 9 10 |
class Test { public static void main(String args[]){ int i = 1; do { i++; System.out.print(i + " "); } while (i < 0); } } |
Commentary: At first, the while loop checks the condition and then executes the code (the body of the loop). On the other hand, the do…while loop first executes the body of the loop and then checks the condition. That’s why the loop body executes the code at least once. First, the actions are specified and the condition "while ( i < o)" is carried out and, only after that, does it check it the condition. In short, the number 2 will be displayed on the screen. And only after this happens is the "while ( i < 0)" checked, because the "2 > 0" loop will be completed. In other words, the "do…while" loop pre-checks the condition.
The general form of the "do…while" loop is as follows:
1 2 3 4 |
do { // actions } while (condition); |
Remember: the "do…while" loop always executes at least once. We saw this clearly in the example above.
The "do…while" loop is a very good and convenient choice when you need to execute some action at least once or, under certain circumstances, when an action needs to be repeated several times.
The "For" loop
The "for loop" is also called the loop “with the counter”.
Let’s say we want to display the following message on the screen:
Awesome!
Awesome!
Awesome!
Awesome!
As you can see, the word “Awesome!” repeats four times. It’s obvious that you need to use a loop, because the same operation is repeated four times:
1. First, we displayed the word “Awesome!” on the screen.
2. Second, we displayed the word “Awesome!” on the screen.
3. Third, we displayed the word “Awesome!” on the screen.
4. Fourth, we again displayed the word “Awesome!” on the screen.
Note: If you know in advance how many times you want the same action to repeat, then you need to use the "for" loop. For instance, in the example above we knew we needed to display the word “Awesome!” four times. So we used the "for" loop.
1 2 3 4 5 6 7 8 |
class Test { public static void main(String args[]){ for (int i = 1; i <= 5; i++) { System.out.println (“Awesome!”); } } } |
Let’s look at this code step by step:
The construction "for (int i =1; i <=5; i++)" in the Java language is like saying “repeat so many times”. In our case: “Repeat from 1 to 5, that is 5 times”.
"int i = 1" is the first attribute and it is responsible for the definition of the initial value. This attribute is called initialization, where "i" is the loop variable.
"i <=5" is the second attribute and it is responsible for the condition under which the loop is executed i.e. the loop will be executed as long as the condition (i.e. the variable "i") doesn’t equal 5.
"i++" is the third attribute and it is responsible for changing the variable "i" after each step of the loop. Our example indicated “i++”, which means that the variable will be increased by one in each step of the loop – from 1 to 2, from 2 to 3, from 3 to 4, and from 4 to 5. This third attribute is called iteration.
The general form of the "for" loop in Java is as follows:
1 2 3 |
for (initialization; condition; iteration) { // actions } |
We suggest that you solve one more task.
Task No. 7
It is necessary to display the numbers from 3 to -3 at the screen i.e. the following numbers should appear on the screen: 3 2 1 0 -1 -2 -3
Solution:
1 2 3 4 5 6 7 8 |
class Test { public static void main (String [] args) { for (int i = 3; i >= -3; i--) { System.out.print (i + " "); } } } |