Course Content
Java Basics
Java Basics
Introduction to Loops
What if we need to repeat a code fragment many times? For example, our boss gave us an incredible task - to display the same message on the screen 1000 times. Can you imagine how you would spend the whole day typing System.out.println();
over and over again?
But here, loops come to the rescue!
Note
In Java, there are several types of loops, each better suited for specific tasks. Throughout the next section, you will explore each of them and understand where and when it is best to use them.
Let's scale down the task a bit and say that we need to display the same message 5 times. We'll use the copy-paste method:
Main
package com.example; public class Main { public static void main(String[] args) { System.out.println("Hey, I will appear here 5 times"); System.out.println("Hey, I will appear here 5 times"); System.out.println("Hey, I will appear here 5 times"); System.out.println("Hey, I will appear here 5 times"); System.out.println("Hey, I will appear here 5 times"); } }
As we can see, we have completed the task and displayed the text on the screen five times.
Now, all we have to do is display this text on the screen only 995 more times, and the task will be complete.
Any programmer looking at our solution method will say that we've gone crazy!
So, let's use a loop that will perform a specific operation until the loop's execution condition becomes false:
Main
package com.example; public class Main { public static void main(String[] args) { int number_of_operations = 0; while (number_of_operations < 10) { System.out.println("Hey, I will appear here 10 times"); number_of_operations = number_of_operations + 1; } } }
In the code above, we used a loop. However, it's worth noting that initially, we declared the variable number_of_operations
to count how many times we performed the operation. Then we set a condition that this variable should have a value less than 10, which means the loop will execute until the variable's value reaches 10. We will explore the operation of specific loop examples in more detail in the following chapters.
Thanks for your feedback!