Java Loops (for) 🎯

beginner
18 min

Java Loops (for) 🎯

Welcome to the Java Loops (for) Tutorial! In this comprehensive guide, we'll dive deep into understanding for loops in Java. By the end of this lesson, you'll have a solid foundation to write clean, efficient, and practical code. Let's get started!

What are Loops in Java? 📝

Loops are essential control structures in programming that allow us to repeat a block of code as many times as needed. In Java, we have two main types of loops: for loops and while loops. Today, we'll focus on the for loop.

Understanding the for Loop Syntax 💡

A for loop consists of three parts separated by semicolons (;):

  1. Initialization: This part declares and initializes the control variable (counter) with an initial value.
  2. Condition: This part defines a boolean condition that determines when the loop should continue iterating.
  3. Increment: This part updates the control variable after each iteration.

Here's a basic for loop structure:

java
for (initialization; condition; increment) { // code to be repeated }

Practical Example: Printing Numbers 1-10 📝

Now, let's put this into practice! We'll create a simple example that prints numbers from 1 to 10 using a for loop.

java
public class ForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(i); } } }

In this example, i is the control variable, initially set to 1. The condition checks if i is less than or equal to 10, and the increment updates i by 1 after each iteration.

Variables and Control Structures within for Loops 💡

You can declare and use variables inside a for loop, as well as include other control structures like if statements and break and continue.

Here's an example that demonstrates these concepts:

java
public class ForLoopExample2 { public static void main(String[] args) { for (int i = 2; i <= 10; i++) { if (isPrime(i)) { System.out.println(i); } } } private static boolean isPrime(int number) { if (number <= 1) return false; for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) return false; } return true; } }

In this example, we've created a helper method called isPrime to check if a number is prime. We're using a nested for loop within the main loop to check if the number is divisible by any numbers up to its square root.

Quiz: Identify the Correct Syntax for a for Loop 🎯

Quick Quiz
Question 1 of 1

What is the correct syntax for a `for` loop in Java?

By now, you should have a good understanding of for loops in Java! In the next lesson, we'll dive deeper into while loops and compare the differences between these two powerful control structures. Keep learning, keep coding! 🚀💻