Lesson 2
Introduction to Java Loops
Topic Overview

Greetings, Explorer! In this lesson, we will delve into the essential tools of Java loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring each cup is brewed quickly and consistently. In this lesson, we will explore the universe of looping in Java and gain hands-on experience by applying loops to Java ArrayLists and Strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

Java
1import java.util.ArrayList; 2 3class Solution { 4 public static void main(String[] args) { 5 ArrayList<String> friends = new ArrayList<>(); 6 friends.add("Alice"); 7 friends.add("Bob"); 8 friends.add("Charlie"); 9 friends.add("Daniel"); 10 11 for (String friendName : friends) { 12 // For each friendName, print the greeting 13 System.out.println("Hello, " + friendName + "! Nice to meet you."); 14 } 15 } 16}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in Java

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop is typically for (initialization; condition; iteration) {loop body}, where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed, which generally updates the value of the loop control variable. Here is how it generally works:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.
  2. Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends, and the flow jumps to the next statement after the loop.
  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.
  4. Loop Body: The block of code to be executed in each loop.

Let's print a range of numbers using a for loop:

Java
1class Solution { 2 public static void main(String[] args) { 3 for (int num = 0; num < 5; num++) { 4 // This line prints numbers from 0 to 4 5 System.out.println(num); 6 } 7 } 8}

In each cycle of the loop, the variable (num) is updated before executing the code inside the block.

Enhanced For Loop in Java

The for loop is versatile and can work with any sequence-like structure in Java, such as strings, arrays, and ArrayLists. In Java, the enhanced for loop, also known as the for-each loop, is used to traverse these collections more simply and safely since it eliminates the need to manually control the loop variable.

Java
1import java.util.ArrayList; 2 3class Solution { 4 public static void main(String[] args) { 5 // ArrayList of fruits 6 ArrayList<String> fruits = new ArrayList<>(); 7 fruits.add("apple"); 8 fruits.add("banana"); 9 fruits.add("cherry"); 10 11 // `fruit` stands for each fruit in the `fruits` ArrayList 12 for (String fruit : fruits) { 13 System.out.println(fruit); // print each fruit 14 } 15 } 16}

In the above example, the fruit variable stands for each element in the fruits ArrayList. The loop body executes once for each item in the fruits ArrayList, with fruit being a reference to the current element in each iteration.

Similarly, we may loop through strings (which are considered containers of characters), using the toCharArray() method to convert the string into an array of characters:

Java
1class Solution { 2 public static void main(String[] args) { 3 String word = "hello"; 4 // 'ch' is each individual character in `word` 5 for (char ch : word.toCharArray()) { 6 System.out.println(ch); // print each character from 'hello' 7 } 8 } 9}

In the example above, ch stands for each character in the word string. The toCharArray() method converts the string into an array of characters so that the enhanced for loop can iterate through each character. The loop repeats for each character in the string word. For each repetition, it will print the specific character, hence printing 'hello' one character at a time.

While Loop in Java

While loops in Java continuously execute their content until a particular condition becomes false. Here's a simple example:

Java
1class Solution { 2 public static void main(String[] args) { 3 int num = 0; 4 // The loop keeps running until num is no longer less than 5 5 while (num < 5) { 6 System.out.println(num); 7 // Increase num by 1 at the end of each iteration 8 num++; 9 } 10 } 11}

As you can see, before each iteration, Java checks the condition (num < 5). If it's true, the loop continues; otherwise, the loop breaks.

Applications of Looping

Loops are integral to programming. They are extensively used in various sections of a program, such as summing elements in an ArrayList and parsing through text.

Java
1import java.util.ArrayList; 2 3class Solution { 4 public static void main(String[] args) { 5 // ArrayList of numbers 6 ArrayList<Integer> numbers = new ArrayList<>(); 7 numbers.add(1); 8 numbers.add(2); 9 numbers.add(3); 10 numbers.add(4); 11 numbers.add(5); 12 13 int total = 0; 14 // `num` is each number in `numbers` 15 for (int num : numbers) { 16 total += num; // Add each number in the ArrayList 17 } 18 System.out.println(total); // print the total sum 19 } 20}
Java
1class Solution { 2 public static void main(String[] args) { 3 String text = "hello"; 4 int vowelCount = 0; 5 // `ch` is each character in `text` 6 for (char ch : text.toCharArray()) { 7 // If a vowel letter is found, increment the count 8 if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { 9 vowelCount++; 10 } 11 } 12 System.out.println(vowelCount); // print the count of vowels 13 } 14}
Lesson Summary and Practice

Congratulations on mastering Java loops! We've brushed up on for and while loops and have seen how to loop over containers like ArrayLists and Strings. Now, it's time for some beneficial practice exercises to solidify your learning. The more problems you solve, the better you'll become. Let's proceed further on our journey into the depths of programming!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.