Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to Loops | Loops
Java Basics
course content

Course Content

Java Basics

Java Basics

1. Getting Started
2. Basic Types, Operations
3. Loops
4. Arrays
5. String

book
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:

java

Main

copy
1234567891011
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:

java

Main

copy
1234567891011
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.

1. What is a loop in java?
2. What is the purpose of loops in Java?
What is a loop in java?

What is a loop in java?

Select the correct answer

What is the purpose of loops in Java?

What is the purpose of loops in Java?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt